所以我试图获取网页中使用的所有单词的数组。
应该很容易吧?
我遇到的问题是$("body").text().split(" ")
返回一个数组,其中一个元素开头的单词和另一个元素结尾的单词连接为一个。
i.e:
<div id="1">Hello
<div id="2">World</div>
</div>
returns ["HelloWorld"]
当我想要它返回时["Hello", "World"]
.
我也尝试过:
wordArr = [];
function getText(target)
{
if($(this).children())
{
$(this).children(function(){getText(this)});
}
else
{
var testArr = $(this).text().split(" ");
for(var i =0; i < testArr.length; i++)
wordArr.push(testArr[i]);
}
}
getText("body");
but $(node).children()
对于 DOM 中存在的任何节点都是 true,所以这不起作用。
我确信我错过了一些明显的东西,所以我希望有一双额外的眼睛。
就其价值而言,我不需要唯一的单词,只需将文档正文中的每个单词作为数组中的元素即可。我试图用它来生成与另一组单词的上下文和词汇共现,因此重复了给定单词的上下文重要性。
预先感谢您的任何想法。
See Fiddle http://jsfiddle.net/wc9QN/
像这样的事情怎么样?
var res = $('body *').contents().map(function () {
if (this.nodeType == 3 && this.nodeValue.trim() != "")
return this.nodeValue.trim();
}).get().join(" ");
console.log(res);
Demo http://jsfiddle.net/n3zB5/
获取单词数组:
var res = $('body *').contents().map(function () {
if (this.nodeType == 3 && this.nodeValue.trim() != "") //check for nodetype text and ignore empty text nodes
return this.nodeValue.trim().split(/\W+/); //split the nodevalue to get words.
}).get(); //get the array of words.
console.log(res);
Demo http://jsfiddle.net/FeP2q/
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)