2017-06-23 19 views
2

我想替換另一個字符串中的字符串。我的問題是,搜索字符串是一個變量,我需要爲此設置一個組,因爲我想重用原始匹配字符串。JS /正則表達式:如何在正則表達式中設置多個替換組?

const string = 'Any string with many words' 
const label = 'any' 
const re = new RegExp(label, 'gi') 

string = string.replace(
    re, 
    '>>>' + $1 + '<<<' 
) 

console.log(string) 
// Expect: >>>Any<<< string with m>>>any<<< words 
+1

使用''>>> $&<<<'' –

回答

1

您需要使用替換模式中反向引用。此外,要訪問整個匹配值,您需要使用$&反向引用,而不是$1$1反向引用可以在整個模式中使用括號(如new RegExp(`(${label})`, 'gi')),但由於存在方便的反向引用,因此不需要該引用。請參閱Specifying a string as a parameter

let string = 'Any string with many words'; 
 
const label = 'any'; 
 
const re = new RegExp(label, 'gi'); 
 

 
string = string.replace(
 
    re, 
 
    '>>>$&<<<' 
 
) 
 

 
console.log(string)

注意,如果你需要修改它的價值string不應該被聲明爲const(我用let以上)。

請注意,如果您的label包含特殊的正則表達式字符,這是一個好主意escape the label value