myString = 'he)llo)';
desiredString --> 'he\)llo\)';
我尝试使用
var desiredString = myString.replace(')', '\\)');
但是desiredString的结果值为'he)llo)'
如何获取上面第二行中显示的 desiredString
值?
最佳答案
试试这个:
var myString = 'he)llo)';
var desiredString = myString.replace(/\)/g, '\\\)');
console.log(desiredString);
/\)/g
是所有出现 )
的全局正则表达式。通常它只是 /<string to replace>/g
,但是我们需要使用 \
逃避)
.
例如:
"my string is my favorite".replace(/my/g, "your");
//your string is your favorite
关于javascript - 将字符串中的末尾括号替换为反斜杠字符,后跟末尾括号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42658268/