从HTML字符串替换span标签和&nbsp

时间:2019-10-15 08:42:22

标签: javascript jquery html

我有这样的HTML代码:

<span>This is HTML.</span>&nbsp; This is &nbsp;&nbsp; paragraph.

我想将span标记与&nbsp;一起替换。

我的输出将是这样的:

This is HTML.This is &nbsp;&nbsp; paragraph.

这是我尝试过的:

myvar = "<span>This is HTML.</span>&nbsp; This is &nbsp;&nbsp; paragraph.";
newContent = myvar.replace(/<\/?span[^>]*>/g,"");

1 个答案:

答案 0 :(得分:0)

只需多次使用replace。因为,除非使用正则表达式,否则它只会替换第一次出现的东西,因此不会丢失多余的&nbsp;


let initialString = '<span>This is HTML.</span>&nbsp; This is &nbsp;&nbsp; paragraph.';
let finalString = initialString.replace('<span>', '').replace('</span>', '').replace('&nbsp;', '');