javascript - JavaScript replace()方法美元符号

标签 javascript string

我有一个类似于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/

相关文章:

arrays - 使用正则表达式进行 Scala 数组模式匹配

c++ - 使用取消引用的字符串类型的 Vector 迭代器作为函数参数

c# - 用于在表中存储日期的字符串由于未知原因正在转换为 int

javascript子字符串帮助

javascript - Xamarin 表单 webview Eval 不调用 javascript

javascript - typeof jQuery.data() 有问题吗?

javascript - 如何附加任何特定标签?

javascript - 使用 switch case 跟踪数组的全局索引

javascript - 仅替换字符串中最后一次出现的位置

Python - 如何突出显示字符串中的单词?