如何获取页面上使用的所有单词的数组

Jas*_*ols 9 javascript jquery

所以我正在尝试获取我的网页中使用的所有单词的数组.

应该很容易吧?

我遇到的问题是$("body").text().split(" ")返回一个数组,其中一个元素的开头和另一个元素的结尾的单词作为一个连接.

即:

<div id="1">Hello
    <div id="2">World</div>
</div>
Run Code Online (Sandbox Code Playgroud)

["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");
Run Code Online (Sandbox Code Playgroud)

$(node).children()对于存在的DOM中的任何节点来说都是真实的,所以这不起作用.

我确定我错过了一些明显的东西,所以我会欣赏一双额外的眼睛.

对于它的价值,我不需要唯一的单词,只需要文档正文中的每个单词作为数组中的元素.我试图使用它来生成与另一组单词的上下文和词汇共现,因此重复了给定单词的上下文重要性.

提前感谢任何想法.

小提琴

PSL*_*PSL 6

这样的事怎么样?

 var res = $('body  *').contents().map(function () {
    if (this.nodeType == 3 && this.nodeValue.trim() != "") 
        return this.nodeValue.trim();
}).get().join(" ");
console.log(res);
Run Code Online (Sandbox Code Playgroud)

演示

获取一系列单词:

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);
Run Code Online (Sandbox Code Playgroud)

演示