Javascript:在一行字符串中获取body html.如何删除换行符

Javascript: Get body html in one row string. How to remove linebreaks?

本文关键字:html body 换行符 删除 获取 何删除 字符串 Javascript 一行      更新时间:2023-09-26

我有html

<span style="font-family: tahoma, arial, helvetica, sans-serif;
font-size: 10pt;">One
two:</span>

我需要在一行字符串中接收html。

a = $("body").clone().find("script").remove().end().html();
a = a.replace("'r'n", "zzz");
a = a.replace("'n", "zzz");
console.log(a);

但是它不起作用。我得到的都一样。

<span style="font-family: tahoma, arial, helvetica, sans-serif;
font-size: 10pt;">One
two:</span>

用regex和全局标志替换所有新行字符:

a.replace(/'r?'n/g, ' ');
演示

问题是这个字符串。replace,只删除您定义的字符串的第一个出现,您需要使用带有global选项的regex:

a = $("body").clone().find("script").remove().end().html();
a = a.replace(/'r'n/g, " ");
a = a.replace(/'n/g, " ");
console.log(a);

VisioN的答案更好,因为它在一个正则表达式中考虑了两种情况,使其更快。