如果替换具有$',则replace方法会产生意外结果

当替换字符串包含$'个字符时,请用奇怪的字符串替换方法结果。


示例: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?


不负相思意
浏览 140回答 2
2回答

郎朗坤

你应该逃避角色replace(regex, "\$")替换目标中的$具有特殊含义:将匹配组放入字符串中
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript