繁体   English   中英

删除HTML标签和格式化文本

[英]Remove HTML tags and formatting text

我想删除文本之间的HTML标记,并将换行符更改为空格。 我在下面使用这种模式,但它并不完美。 它在文本之间添加两个或多个空间。 如何解决这种模式?

replace(/(&nbsp;|<([^>]+)>)/ig, ' ');

尝试下面的代码并检查

replace(/(<([^>]+)>)/ig,"");

UPDATE

你可以这样

var html = 'Example: &nbsp;<h1></h1><p></p><div>&nbsp;</div><div>CONTENT</div>&nbsp;';
html = html.replace(/\s|\n|&nbsp;/g, ' ');
html = html.replace(/<[^>]+>/gm, '');

输出将是这样,

Example:   CONTENT 

尝试以上解决方案,您将成功。

这是我将要执行的操作:
(请参见我的摘录中的评论)

 // Input data var input_data = `My<div><br> <span></span> <span></span> </div><p>Content</p>`; console.log("Input:", input_data); // Creates html element with Input data var elm = document.createElement('div'); elm.innerHTML = input_data; // Use native function '.innerText' to get rid of the html, // then replace new lines by spaces, and multiple spaces by only one space output_data = elm.innerText.replace(/\\n/g, ' ').replace(/[\\s]+/g, ' '); console.log("Output:", output_data); 

希望能帮助到你!

暂无
暂无

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

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