我们使用 JS 加载 JSON 数据,这些数据通常在换行符之前有多个反斜杠。示例:
{
"test": {
"title": "line 1\\\\\\\nline2"
}
}
我使用替换尝试了各种正则表达式模式。 “奇怪的是”,如果有偶数个反斜杠,它们似乎可以工作,但不是奇数。
这个带有 2 个反斜杠的示例有效:
"\\n".replace(/\\(?=.{2})/g, '');
虽然这个带有 3 的示例没有:
"\\\n".replace(/\\(?=.{2})/g, '');
这是正在运行的 js:
console.log('Even Slashes:');
console.log("\\n".replace(/\\(?=.{2})/g, ''));
console.log('Odd Slashes:');
console.log("\\\n".replace(/\\(?=.{2})/g, ''));
最佳答案
我认为您正在尝试删除换行符之前的所有反斜杠:str.replace(/\\+\n/g, "\n")
。
另外,你可能会误解how escape sequences work :
"\\"
是一个反斜杠"\\n"
是一个反斜杠后跟字母 n
请参阅下面的代码以获取解释,并注意 Stack Overflow 的控制台输出正在重新编码字符串,但如果您检查实际的开发工具,它会更好并显示编码的字符。
const regex = /\\+\n/g;
// This is "Hello" + [two backslashes] + "nworld"
const evenSlashes = "Hello\\\\nworld";
// This is "Hello" + [two backslashes] + [newline] + "world"
const oddSlashes = "Hello\\\\\nworld";
console.log({
evenSlashes,
oddSlashes,
// Doesn't replace anything because there's no newline on this string
replacedEvenSlashes: evenSlashes.replace(regex, "\n"),
// All backslashes before new line are replaced
replacedOddSlashes: oddSlashes.replace(regex, "\n")
});
关于javascript - 使用 javascript 正则表达式删除多个反斜杠,同时保留\n 特殊字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55816623/