简体   繁体   English

如何仅将数字和/或单词从字符串拆分为Javascript中的数组

[英]How to split only the numbers and/or words from a string into an array in Javascript

I have the string "1, 2, 3" and the string "1, 2, 3 Go!" 我有字符串"1, 2, 3"和字符串"1, 2, 3 Go!" I would like to split into an array that only includes the numbers or the words without the punctuation. 我想拆分成一个仅包含数字或单词而不包含标点符号的数组。

So first one becomes ["1", "2", "3"] 所以第一个变成["1", "2", "3"]

The second one becomes ["1","2","3", "Go"] 第二个变成["1","2","3", "Go"]

I can get the first one by "1, 2, 3".split(/[^0-9]/).filter(function(value){if(value) return value;} 我可以通过"1, 2, 3".split(/[^0-9]/).filter(function(value){if(value) return value;}得到第一个"1, 2, 3".split(/[^0-9]/).filter(function(value){if(value) return value;}

I use filter because I get ["1", "", "2", "", "3"] when I just use split . 我使用filter是因为当我只使用split时会得到["1", "", "2", "", "3"]

I don't know who to get the second array. 我不知道谁能得到第二个数组。

Is there a regular expression pattern that will only split the string into either numbers and or words? 是否存在仅将字符串分成数字和/或单词的正则表达式模式?

这个怎么样:

"1, 2, 3 Go!".match(/\d+|[a-zA-Z]+/g) //outputs ["1", "2", "3", "Go"]

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

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