Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

327
Views
How to combine two regular expressions into one with different $1?

I have two regular expressions with different $1. In the first part, there is a slash before $1, but there is no slash in the second part. How then to combine them into one expression?

const url = 'http://localhost////example///author/admin?query=1212';
clean_url = url.replace(/($|\?)/, "/$1").replace(/([^:]\/)\/+/g, "$1")
console.log(clean_url)

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Since this question is asking about @nuxtjs/redirect-module, you can use multiple redirects:

redirect: [{
  from: '(.*)($|\?)(.*)',
  to: '$1/$2$3'
}, {
  from: '(.*)([^:]\/)\/+(.*)',
  to: '$1$2$3'
}]

or a replace function

redirect: [{
  from: '.*(?:(?:$|\?)|(?:[^:]\/\/+)).*',
  to: from => from.replace(/($|\?)/, "/$1").replace(/([^:]\/)\/+/g, "$1")
}]
about 4 years ago · Juan Pablo Isaza Report

0

You can use

const url = 'http://localhost////example///author/admin';
clean_url = url.replace(/($|\?)|([^:]\/)\/+/g, (x,y,z) => z ? z : '/' + y);
console.log(clean_url);
// => http://localhost/example/author/admin/

The ($|\?)|([^:]\/)\/+ regex matches

  • ($|\?) - Group 1 (y): end of string or ?
  • | - or
  • ([^:]\/)\/+ - any char other than : and a / (Group 2, z), and then one or more slashes.

If Group 2 matches, the replacement is Group 2 value, else, the replacement is / + Group 3 value.

about 4 years ago · Juan Pablo Isaza Report

0

It is not possible to just "combine" these two regular expressions, but you can combine the tasks, as both are just inserting a single / with different conditions.

You can combine the logic with lookbehinds (which may not be available in every browser yet) and the expression is an abomination and I'd be careful about performance in production; But it is possible ;)

const url = 'http://localhost////example///author/admin?query=1212';
clean_url = url.replace(/(?<!\?.*)(?<![:\/])(?:\/+|\/*(?=\?)|\/*$)/g, "/")
console.log(clean_url)

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!