我有这个 HTML 数据
<div id="sample">
<p style="text-align: center;">
<span style="font-family: 'comic sans ms', sans-serif; font-size: medium;">
<strong>
word1
<span style="line-height: 1.5;">
word2
</span>
<span style="line-height: 1.5;">
word3
</span>
<span style="line-height: 1.5;">
</span>
</strong>
</span>
</p>
</div>
我想获取 div
元素内的文本。
这是我的 JavaScript 代码:
var text = document.getElementById('sample');
var text_content = jQuery(text).text();
console.debug(text_content);
控制台记录word1 word2 word3
。
我想要逐字解析,所以我使用了split
方法:
var text_content_array = text_content.split(" ");
console.debug(text_content_array);
控制台记录["word1 word2 word3"]
。该字符串未标记化。
我尝试了这段代码,但没有成功:
var text_content_array = text_content.split(" \n\r\t\b\f");
console.debug(text_content_array);
我该怎么做才能从字符串中获取单词数组?
最佳答案
您可以使用trim方法和正则表达式来获取数组。
类似的东西:console.log(text_content.trim().split(/[\s,]+/))
这是 jsbin example用你的代码。
关于javascript - 将文本拆分为单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37456296/