将 JavaScript 字符串中的每个反斜杠替换为不同的字符

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

如何在不使用模板文字的情况下将 JavaScript 字符串中的每个 \ 字符替换为不同的字符?

myString 的示例:

let myString = "This\ \is \\ my \\\\\String";

我尝试过使用以下线路:

let result = myString.replace(/\\/g, "-");
但是,这会将每 2 个反斜杠替换为破折号

我尝试过使用以下线路:

let result = myString.replace(/\/g, "-");
但是,这会产生错误

我尝试过使用

String.raw()
功能。但是,这仅适用于模板文字字符串。我无法使用模板文字

javascript string replace backslash
1个回答
0
投票

字符串中的单个反斜杠 (

\
) 被解释为字符转义。每个不是字符转义的
\
都应该自行转义。

// in myString, \, \i, \w, \S are interpreted as escape sequences
const myString = "This\ \is \\ my \\\\\String";;
// so this won't work
console.log(myString.replace(/\\/g, `-`));

// every '\' should be escaped on itself in a string
const myStringOk = "This\\ \\is \\\\ my \\\\String";;
// now it works
console.log(myStringOk.replace(/\\/g, `-`));

© www.soinside.com 2019 - 2024. All rights reserved.