简体   繁体   English

Javascript 全部替换在 macOS/iOS 上的 safari 中不起作用

[英]Javascript replace all doesn't work in safari on macOS/iOS

I got below error in safari on macOS/iOS我在 macOS/iOS 上的 safari 中遇到以下错误

Consider I need to replace a placeholder with actual price考虑我需要用实际价格替换占位符

const formattedPrice = '$1,100.00';
str.replace( /\|\|TOTAL_REPAYMENT_CHARGES\|\|/g, formattedPrice);

the result of above would be ,100.00上面的结果将是,100.00

but if i use below one, it works但如果我使用低于一个,它的工作原理

const formattedPrice = '$1,100.00';
str.replace( '||TOTAL_REPAYMENT_CHARGES||', formattedPrice)

the result would be $1,100.00结果将是$1,100.00

can someone explain what happened?有人可以解释发生了什么吗? thanks谢谢

When the first parameter of .replace is a regular expression, and the second parameter of .replace is a string, JS will parse the second parameter according to some rules , allowing for the concise replacement with the full match or a capture group..replace的第一个参数是正则表达式,而.replace的第二个参数是字符串时,JS 会根据一些规则解析第二个参数,允许使用全匹配或捕获组进行简洁的替换。 For example, $& indicates to replace with the full match:例如, $&表示替换为完整匹配:

 console.log('foo'.replace(/o/g, 'a$&'));

Above, each match is replaced with a , followed by the full match, and both full matches are o , so both matches are replaced with ao .上面,每个匹配都用a替换,然后是完整匹配,并且两个完整匹配都是o ,因此两个匹配都替换为ao

In your code, the $1 is being interpreted as "replace this part with the first capture group".在您的代码中, $1被解释为“用第一个捕获组替换这部分”。 But your code doesn't have any capture groups, so instead of matches being replaced with '$1,100.00' , they get replaced with ',100.00' .但是您的代码没有任何捕获组,因此匹配项不是替换为'$1,100.00' ,而是替换为',100.00'

To indicate a literal $ , use two $ s, like this:要指示文字$ ,请使用两个$ ,如下所示:

const formattedPrice = '$$1,100.00';
//                       ^
str.replace( /\|\|TOTAL_REPAYMENT_CHARGES\|\|/g, formattedPrice);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM