[英]Extract arrays of characters in String in Javascript
I've looked around and practiced my RegEx but I still can't get it right... Probably a noob question How would I split a string to only keep the words (a to z) and only them, split by any other character? 我环顾四周并练习了RegEx,但仍然无法正确操作...可能是一个菜鸟问题,我该如何分割字符串以仅保留单词(a到z),并仅保留它们,并用其他任何字符分割?
hello3you ?! hey 32 foo
would return 会回来
["hello","you","hey","foo"]
I tried the following, no luck: 我尝试了以下方法,没有运气:
var words = itemObject["name"].toLowerCase().split(/^([a-z]+)/g);
var words = itemObject["name"].toLowerCase().split(/[a-zA-Z]+/g);
Thanks 谢谢
Instead of splitting you should think of it as a matching operation; 与其拆分,不如将其视为匹配操作。 after all, the title of your question is about extracting strings:
毕竟,您的问题的标题与提取字符串有关:
'hello3you ?! hey 32 foo'.match(/[a-z]+/ig);
This will return an array of strings matching a "bunch of letters". 这将返回与“字母束”匹配的字符串数组。
[^a-z]+
您可以以此分割以获得所需的结果。
I'd suggest: 我建议:
var matches = "hello3you ?! hey 32 foo!".split(/[^az]+/).filter(function(el) { if (el.length) { return el; } }); console.log(matches);
[^az]
is a range of characters that are not az (inclusive), [^az]
是未 AZ个字符的范围内(含), +
requires a match of one, or more, of those characters. +
要求匹配一个或多个这些字符。 试试: var words = itemObject["name"].toLowerCase().split(/([^az]+)/);
Working: 工作:
var words = itemObject["name"].match(/[az]+/ig); var words = itemObject [“ name”]。match(/ [az] + / ig);
Output: 输出:
hello,you,hey,foo
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.