简体   繁体   中英

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)

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

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM