本文介绍了JS:从没有jQuery的字符串中提取文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个字符串:
var string = '<article><img alt="Ice-cream" src=http://placehold.it/300x300g"><div style="float: right; width: 50px;"><p>Lorem Ipsum </p></div></article>';
我试图从中提取文本:
var $str = $(string).text();
console.log($str)
但是因为我担心由于大量文字的大量字符串而导致的表现,所以我想要本地化。
but since I am concerned about performance due to a huge amount of strings with big text, I would want to go natively.
这怎么可能?
推荐答案
让浏览器进行卫生并使用此技巧:
Let the Browser do the sanitation and use this trick:
var str= '<article><img alt="Ice-cream" src=http://placehold.it/300x300g">'+
'<divstyle="float: right; width: 50px;"><p>Lorem Ipsum </p></div></article>';
var dummyNode = document.createElement('div'),
resultText = '';
dummyNode.innerHTML = str;
resultText = dummyNode.innerText || dummyNode.textContent;
这会创建一个虚拟DOM元素并将其HTML内容设置为输入字符串。
现在只需调用DOM属性 innerText
或 textContent
即可获得唯一的文本。
This creates a dummy DOM element and sets its HTML content to the input string.
Now the only text can be got by simply calling the DOM property innerText
or textContent
.
这也更加安全和稳健,因为浏览器已经编写了更好的算法来获取这些值。
This is also more safe and robust as Browser has already written better algorithms to get these values.
这篇关于JS:从没有jQuery的字符串中提取文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!