javascript - 使用 javascript 正则表达式删除多个反斜杠,同时保留\n 特殊字符

标签 javascript json regex

我们使用 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")
});

enter image description here

关于javascript - 使用 javascript 正则表达式删除多个反斜杠,同时保留\n 特殊字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55816623/

相关文章:

javascript - 如何在 gridview 图像按钮内使用模态弹出扩展器?

java - 使用 JSON Path 从数组中提取值

regex - 在 Groovy 中查找小写单词

java - java中的正则表达式 _ 是什么意思

javascript - 防止更改 Javascript 原型(prototype)对象中的属性值

javascript - Firebase 未与 React 应用程序连接 - 权限被拒绝 - 在线检查了所有关于此无解决方案的问题

javascript - 用jquery生成表

json - 使用 postman 发送 json api 对象

json - 通过 HTTP POST 编码二进制数据的最有效方法是什么

java - 匹配完整文件正则表达式中的 A 部分,但不匹配 B 部分