Home > Back-end >  How to combine two regular expressions into one with different $1?
How to combine two regular expressions into one with different $1?

Time:02-21

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)

CodePudding user response:

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")
}]

CodePudding user response:

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.

CodePudding user response:

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)

  • Related