JavaScript中的字符串分割?

4
我正在使用my_colors.split(" ")方法,但我想将字符串按固定的单词数拆分或分割,例如每10个单词后进行一次拆分...如何在JavaScript中实现这一点?
4个回答

7
尝试这个 - 这个正则表达式捕获长度为十个单词(或者对于最后的单词,长度小于等于十个单词)的组:
var groups = s.match(/(\S+\s*){1,10}/g);

天啊!你的答案比我的漂亮多了,我都有点尴尬了!Sheery,如果你不接受这个答案,我就要踢一只小狗了。 - jessegavin
2
@sheery 如果你喜欢这个答案,为什么不接受它呢?你应该始终接受你认为最有帮助的答案,这样下一个遇到同样问题的人就会知道哪个解决方案是“最好的”,或者至少被提问者认为是最好的。 - Josh Mein

3

如果单词之间由多个空格或其他空白字符分隔,您可以使用正则表达式/\S+/g来拆分字符串。

我不确定下面的示例是否是最优雅的方法,但它可以工作。

<html>
<head>
<script type="text/javascript">
    var str = "one two three four five six seven eight nine ten "
                        + "eleven twelve thirteen fourteen fifteen sixteen "
                        + "seventeen eighteen nineteen twenty twenty-one";

    var words = str.match(/\S+/g);
    var arr = [];
    var temp = [];

    for(var i=0;i<words.length;i++) {
        temp.push(words[i]);
        if (i % 10 == 9) {
            arr.push(temp.join(" "));
            temp = [];
        }
    }

    if (temp.length) {
        arr.push(temp.join(" "));
    }

    // Now you have an array of strings with 10 words (max) in them
    alert(" - "+ arr.join("\n - "));
</script>
</head>
<body>
</body>
</html>

1
切片在这里非常方便:http://www.w3schools.com/jsref/jsref_slice_array.asp - Kobi
切片做得不错。然而,我必须把我的答案打印出来才能烧掉它。你的好多了。 - jessegavin
谢谢"jessegavin",它做了我想要的事情,非常感谢。 - Sheery

2
你可以将结果数组分割(" "),然后每次以10个元素为单位合并(join)。

0
你可以尝试类似这样的东西。
console.log("word1 word2 word3 word4 word5 word6"
                .replace(/((?:[^ ]+\s+){2})/g, '$1{special sequence}')
                .split(/\s*{special sequence}\s*/));
//prints  ["word1 word2", "word3 word4", "word5 word6"]

但是你最好使用split(" "),然后再使用join(" "),或者编写一个简单的分词器,以任何你喜欢的方式对这个字符串进行分割。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接