gpt4 book ai didi

javascript - 将字符串中的单词提取到数组中

转载 作者:行者123 更新时间:2023-12-01 02:21:54 26 4
gpt4 key购买 nike

我想从字符串中提取所有单词并将它们放入数组中。

“单词”是指一系列连续的字母。如果我有空格或其他字符,则该单词就在那里结束。

例如,如果我有这个字符串:

"my name is sil/ves tru, what?is." 

我想要一个像这样的数组:

arr[0] = "my";
arr[1] = "name";
arr[2] = "is";
arr[3] = "sil";
arr[4] = "ves";
arr[5] = "tru";
arr[6] = "what";
arr[7] = "is";

这是我目前拥有的:

var str = "my name is sil/ves tru, what?is."; //my string
var i;
var arr = [];
for (i = 0; i < str.length; i++) { //check all positions
if ((str[i] >= "a") && (str[i] <= "z")) { //check where string don't have letter and put the word in arr
//help me here
}
}
console.log(arr); //my array with words

最佳答案

您可以使用正则表达式来拆分任何连续的非字母序列。

var str = "my name is sil/ves tru, what?is.";
var arr = str.split(/[^a-z]+/i).filter(Boolean); // or .filter(s=>s)
console.log(arr);

关于javascript - 将字符串中的单词提取到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49140124/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com