简体   繁体   English

如何替换字符串 JavaScript 中的转义字符

[英]How to replace escape characters in a string JavaScript

I'm using Cheerio to get HTML from a local news website.我正在使用 Cheerio 从本地新闻网站获取 HTML。 When it returns the response, it keeps the escape literals ( \\n, \\t , etc.) in the string.当它返回响应时,它会在字符串中保留转义文字( \\n, \\t等)。 Is there a way to use JS regex to replace all of these characters?有没有办法使用 JS 正则表达式来替换所有这些字符? I've tried using the replace() function but it doesn't seem to replace all of them.我试过使用replace()函数,但它似乎并没有替换所有这些。

Example of the title of the news article I receive back (in json form): " \\n\\t\\t\\t\\t\\t\\t\\t\\t\\t [news article title here] \\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t :我收到的新闻文章标题示例(以 json 形式):" \\n\\t\\t\\t\\t\\t\\t\\t\\t\\t [此处的新闻文章标题] \\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t

Expected output: "[news article here]"预期输出:“[此处的新闻文章]”

Thanks.谢谢。

Try using a regex with a global selector.尝试使用带有全局选择器的正则表达式。 See the g in the following regex, which will get all instances of tabs or breaks replaced.请参阅以下正则表达式中的g ,它将替换所有制表符或中断的实例。

 str.replace(/(\n|\t)/g, '');

Here is a stackblitz with this working.是一个关于这项工作的堆栈闪电战。

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

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