如何使用replace()插入反斜杠(\)字符?

问题描述 投票:0回答:1

我想在replace循环中使用forEach函数,但是它不起作用:

var x = [".em", ".one"];
x.forEach((val, index) => {
  console.log(val.replace(".", "\."));
});
javascript jquery
1个回答
3
投票

问题是因为\字符是JS中的escape character。如果要在字符串中输出实际的\,则需要使用其中两个:

var x = [".em", ".one"];
x.forEach((val, index) => {
  console.log(val.replace(".", "\\."));
});
© www.soinside.com 2019 - 2024. All rights reserved.