将文字拆分为单词

时间:2016-05-26 09:05:39

标签: javascript jquery html split

我有这个HTML数据

<div id="sample">
    <p style="text-align: center;">
        <span style="font-family: 'comic sans ms', sans-serif; font-size: medium;">
            <strong>
                word1&nbsp;
                <span style="line-height: 1.5;">
                    word2&nbsp;
                </span>
                <span style="line-height: 1.5;">
                    word3&nbsp;
                </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); 

如何从字符串中获取一系列单词?

5 个答案:

答案 0 :(得分:0)

您可以使用trim方法和regex来获取数组。

类似的东西:console.log(text_content.trim().split(/[\s,]+/))

这是你的代码的jsbin example

答案 1 :(得分:0)

试试这个: -

var text = document.getElementById('sample');
        var text_content = jQuery(text).text();

        var text_content_array = new Array(); 
        text_content_array = text_content.split(" ");
        for (var i = 0; i < text_content_array.length; i++) {
            if (text_content_array[i].trim().length > 0)
                console.debug(text_content_array[i]);
        }

希望这会对你有所帮助。

答案 2 :(得分:-1)

试试这个

var text_content_array = text_content.split(/&nbsp;|\b\s+/g);

答案 3 :(得分:-1)

试试这个

var a = $("#sample").text().trim();
var b = a.replace(/\s+/g,',');
var c = b.split(',')
alert(c);

https://jsfiddle.net/sum1/xyp3cn37/1/

答案 4 :(得分:-2)

换行符和不间断空格与字符串" "不匹配,但 匹配正则表达式模式\s

从文本中收集所有单独单词的最简单方法是使用match()查找所有非空格字符序列(\S)。该方法避免了在拆分字符串之前修剪字符串的需要。喜欢这个

var text = document.getElementById('sample');
var text_content_array = jQuery(text).text().match(/\S+/g);
console.debug(text_content_array);

输出

["word1", "word2", "word3"]
相关问题