简体   繁体   English

Javascript 将正则表达式 \\\\n 替换为 \\n,\\\\t 替换为 \\t,\\\\r 替换为 \\r 等等

[英]Javascript replace regexp \\n with \n, \\t with \t, \\r with \r and so on

I'm having an HTML Input field where the user can enter a delimiter.我有一个 HTML 输入字段,用户可以在其中输入分隔符。

This delimiter can include \\n, \\t, \\r and so on.此分隔符可以包括\\n, \\t, \\r等。 When I append the delimiter to a string in javascript it is appended as \\n instead of as a newline character.当我将分隔符附加到 javascript 中的字符串时,它会附加为 \\n 而不是换行符。

While I can use str.replace(/\\\\n/g, "\\n") and so on to replace one variation it does not work if I write a general catch-all regexp like str.replace(/\\\\([az])/g, "\\$1") since this just replaces \\n with \\n again.虽然我可以使用str.replace(/\\\\n/g, "\\n")等来替换一个变体,但如果我编写一个像str.replace(/\\\\([az])/g, "\\$1")因为这只是再次用 \\n 替换了 \\n。

How do I have to rewrite the RegExp to replace all double backslashes in front of a character?我如何重写 RegExp 以替换字符前面的所有双反斜杠?

There is no shortcut to replace literals with escaped sequences but you may be able to use this:没有用转义序列替换文字的快捷方式,但您可以使用它:

 const cmap = {'n': '\\n', 't': '\\t', 'r': '\\r'} var str = `value1\\rvalue2\\tvalue3\\nvalue4` str = str.replace(/\\\\([nrt])/g, m => {return cmap[m[1]]}) console.log(str)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM