首页 > 解决方案 > 使用 javascript 正则表达式删除多个反斜杠,同时保留 \n 特殊字符

问题描述

我们正在使用 JS 加载 JSON 数据,这些数据通常在换行符之前有多个反斜杠。例子:

{
    "test": {
        "title": "line 1\\\\\\\nline2"
    }
}

我已经使用替换尝试了各种正则表达式模式。“奇怪”,如果有偶数个反斜杠,它们似乎可以工作,但不是奇数。

这个带有 2 个反斜杠的示例有效:

"\\n".replace(/\\(?=.{2})/g, '');

虽然这个样本,with 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, ''));

标签: javascriptjsonregex

解决方案


我认为您正在尝试删除换行符之前的所有反斜杠:str.replace(/\\+\n/g, "\n")

此外,您可能会误解转义序列的工作原理

  • "\\"是一个反斜杠

  • "\\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")
});

在此处输入图像描述


推荐阅读