[英]How to combine two regular expressions into one with different $1?
我有兩個具有不同 $1 的正則表達式。 在第一部分中,$1 之前有一個斜線,但在第二部分中沒有斜線。 那么如何將它們組合成一個表達式呢?
const url = 'http://localhost////example///author/admin?query=1212'; clean_url = url.replace(/($|\?)/, "/$1").replace(/([^:]\/)\/+/g, "$1") console.log(clean_url)
由於此問題詢問的是@nuxtjs/redirect-module ,因此您可以使用多個重定向:
redirect: [{
from: '(.*)($|\?)(.*)',
to: '$1/$2$3'
}, {
from: '(.*)([^:]\/)\/+(.*)',
to: '$1$2$3'
}]
或更換 function
redirect: [{
from: '.*(?:(?:$|\?)|(?:[^:]\/\/+)).*',
to: from => from.replace(/($|\?)/, "/$1").replace(/([^:]\/)\/+/g, "$1")
}]
您可以使用
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/
($|\?)|([^:]\/)\/+
正則表達式匹配
($|\?)
- 第 1 組 ( y
):字符串結尾或?
|
- 或者([^:]\/)\/+
- 除:
和/
(Group 2, z
) 之外的任何字符,然后是一個或多個斜杠。 如果 Group 2 匹配,則替換為 Group 2 值,否則,替換為/
+ Group 3 值。
僅僅“組合”這兩個正則表達式是不可能的,但您可以組合這些任務,因為兩者都只是插入一個/
具有不同的條件。
您可以將邏輯與 lookbehinds 結合起來(這可能還不是在每個瀏覽器中都可用)並且表達式是令人厭惡的,我會小心生產中的性能; 但這是可能的;)
const url = 'http://localhost////example///author/admin?query=1212'; clean_url = url.replace(/(?<?\.?*)(:<?[:\/])(??\/+|\/*(,=\.)|\/*$)/g, "/") console.log(clean_url)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.