gpt4 book ai didi

javascript - 如果替换有 $',replace 方法会产生意想不到的结果

转载 作者:行者123 更新时间:2023-11-29 22:58:38 25 4
gpt4 key购买 nike

当替换字符串有$'字符时,将方法结果替换为奇怪的字符串。

示例:https://jsfiddle.net/1jns2eo9/


var p = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?';

var regex = /dog/gi;

document.getElementById('first').innerHTML = p.replace(regex, '$');
/// The quick brown fox jumps over the lazy $. If the $ reacted, was it really lazy?
document.getElementById('second').innerHTML = p.replace(regex, "$'");
/// The quick brown fox jumps over the lazy . If the dog reacted, was it really lazy?. If the reacted, was it really lazy? reacted, was it really lazy?

最佳答案

你应该使用

来转义这个字符
replace(regex, "\$")

替换目标中的$有特殊含义:将匹配组放入字符串

关于javascript - 如果替换有 $',replace 方法会产生意想不到的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56077596/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com