javascript - 使用 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, ''));
解决方案
我认为您正在尝试删除换行符之前的所有反斜杠: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")
});
推荐阅读
- c# - 检查网站上的关键字时,循环不会继续运行
- hybris - 已在另一个窗口中登录时出现服务器错误
- javascript - How to test ES6 modules (these with import) with mocha?
- html - 边框只有 div 的一半
- php - 如何在php中的多维数组中搜索针?
- excel - GAS - 基本脚本
- javascript - 有没有办法从标签中删除斜体样式而不影响 document.execCommand("italic")
- php - PHP 类型化属性批量声明不能将 null 分配给可为空的字段
- angular - 在 @ViewChild 变量中使用 spyOn 时出错
- java - 为什么我用可序列化保存后两个对象不相等