我有一个类似于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'
为什么第一种情况和第二种情况相同,并且当我使用
$$$
而不是$$
时得到了预期的结果?
最佳答案
这是因为$$
插入了"$"
。
因此,您需要使用:
a = "aman/gupta";
a = a.replace("/", "$$$$"); // "aman$$gupta"
请参阅以下special patterns:
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.
关于javascript - JavaScript replace()方法美元符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60143703/