我有一个字符串aman/gupta,我想替换它aman$$gupta,为此我使用JavaScript replace方法如下:
let a = "aman/gupta"
a = a.replace("/", "$")
console.log(a) // 'aman$gupta'
a = "aman/gupta"
a = a.replace("/", "$$")
console.log(a) // 'aman$gupta'
a = "aman/gupta"
a = a.replace("/", "$$$")
console.log(a) // 'aman$$gupta'Run Code Online (Sandbox Code Playgroud)
为什么第一和第二种情况相同,当我使用$$$而不是$$?时,我得到了预期的结果?
这是因为$$插入一个"$".
所以,你需要使用:
a = "aman/gupta";
a = a.replace("/", "$$$$"); // "aman$$gupta"
Run Code Online (Sandbox Code Playgroud)
请参阅以下特殊模式:
Pattern Inserts
$$ Inserts a "$".
$& Inserts the matched substring.
$` Inserts the portion of the string that precedes the matched substring.
$' Inserts the portion of the string that follows the matched substring.
$n Where n is a non-negative integer lesser than 100, inserts the nth
parenthesized submatch string, provided the first argument was a
RegExp object.
Run Code Online (Sandbox Code Playgroud)
此外,您可以使用split并join获得更好的性能,$并不是这些功能的特殊功能.
var a = "aman/gupta"
a = a.split('/').join('$$')
alert(a); // "aman$$gupta"
Run Code Online (Sandbox Code Playgroud)
小智 5
为了避免转义特殊字符的需要,您可以使用匿名函数作为替换器
a = "aman/gupta";
a = a.replace("/", function() {return "$$"});
console.log(a); // "aman$$gupta"
Run Code Online (Sandbox Code Playgroud)
将函数指定为参数
您可以指定一个函数作为第二个参数。在这种情况下,将在执行匹配后调用该函数。函数的结果(返回值)将用作替换字符串。(注意:上述特殊替换模式不适用于这种情况。)请注意,如果第一个参数中的正则表达式是全局的,则该函数将针对每个要替换的完整匹配被多次调用。