简体   繁体   English

如何拆分每个单词和空格?

[英]How to split on every word and white space?

I'm trying to split simple contentText(from a span element) with white spaces but for some reason it doesn't split all white spaces. 我试图用白色空格分割简单的contentText(来自span元素)但由于某种原因它不会分割所有的空格。

My algorithm is working properly with the other elements like input texts. 我的算法与输入文本等其他元素一起正常工作。 Did some research for hours now but I couldn't find the result that I need. 现在做了几个小时的研究,但我找不到我需要的结果。

var list_topic = table.find('.list_topic')[0].textContent;
var check_topic = list_topic.split(" ");
console.log(check_topic);

The code above returns: 上面的代码返回:

["    ","word ","word    ","word","  ","word "]

Desired Output" 期望的输出“

["","","","","","word","","word","","","","","word","","","","word",""]```

You could take a regular expression which looks for white space. 你可以采用寻找空格的正则表达式。

 var string = ' word word word \\nword'; console.log(string.split(/\\s/)); 

Try this: 尝试这个:

var check_topic = list_topic.split("");
for (var i = 0; i < check_topic) {
    if (check_topic[i] == " ") {
        check_topic[i] = "";
    } else if (check_topic[i-1] != "") {
        check_topic[i-1] += check_topic[i];
        check_topic.splice(i,1);
    }
}

This takes a string and splits it by every single character. 这需要一个字符串并按每个字符分割它。 If it's whitespace, then it removes it and makes it "" instead of " ". 如果它是空格,则将其删除并使其成为“”而不是“”。 Then, if it's not, AND the last one in the array isn't, it joins the 2. So, something like word would look like this: 然后,如果不是,并且数组中的最后一个不是,则它加入2.所以,像word这样的东西看起来像这样:

[" ", "w","o","r","d"]
["", "w","o","r","d"]
["", "wo","r","d"]
["", "wor","d"]
["", "word"]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM