在JS中使用RegExp来替换任何html标签,其中只包含空格内的空格(相同数量)

时间:2015-10-23 13:09:22

标签: javascript regex

我想在JS中使用RegExp来替换任何html标签,其内部只包含空格(' ' ),其html编码等效 

例如:

替换

'<strong> &nbsp; &nbsp; </strong>' => '&nbsp; &nbsp;'

另一个例子,

替换:

'<strong>&nbsp; &nbsp; &nbsp;</strong> => '&nbsp; &nbsp; &nbsp;'

2 个答案:

答案 0 :(得分:3)

您可以使用这样的正则表达式:

tpx = Vectorize(tpx)

说明:

str = str.replace(/<(\w+)>((?:&nbsp;|\s)+)<\/\1>/g, '$2');

匹配由<(\w+)> matches the start tag and captures the name ( group to capture the content (?:&nbsp;|\s)+ matches &nbsp; or whitespace, one or more times ) ends group <\/\1> matches the end tag with the name of the start tag 替换,即第二组中的值,即标记内的内容。

答案 1 :(得分:0)

让我们说你有字符串

var string = "<strong>&nbsp; &nbsp; &nbsp; </strong> <strong>no</strong>";

仅匹配您可以使用的spaces&nbsp;

var result = string.replace(/<[^>]+>((&nbsp;| )+)<\/[^>]+>/gm, "$1");

让我解释一下,<[^>]+>匹配任何标记和<\/[^>]+>任何结束标记。 (&nbsp;| )+匹配空格或多次