我试图用空格分隔简单的contentText(来自span元素),但由于某种原因,它不能分隔所有空格。
我的算法可以与其他元素(例如输入文本)一起正常工作。现在做了几个小时的研究,但找不到所需的结果。
var list_topic = table.find('.list_topic')[0].textContent;
var check_topic = list_topic.split(" ");
console.log(check_topic);
上面的代码返回:
[" ","word ","word ","word"," ","word "]
["","","","","","word","","word","","","","","word","","","","word",""]```
答案 0 :(得分:3)
您可以使用查找空白的正则表达式。
var string = ' word word word \nword';
console.log(string.split(/\s/));
答案 1 :(得分:0)
尝试一下:
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);
}
}
这需要一个字符串,并按每个字符将其分割。如果是空格,则将其删除并将其设为“”而不是“”。然后,如果不是,并且数组中的最后一个不是,它将连接2。因此,类似word的内容将如下所示:
[" ", "w","o","r","d"]
["", "w","o","r","d"]
["", "wo","r","d"]
["", "wor","d"]
["", "word"]