[英]Javascript Regex to select every non-alphanumeric character AND whitespace?
I'm new to JS, tried using - 我是JS新手,尝试使用-
/[0-9a-z]+$/gi
/[^0-9a-z]+$/gi
neither worked. 都不起作用。 Can anyone tell me where I am going wrong?
谁能告诉我我要去哪里错了?
Replace 更换
var sentence_split = arr.split(/[0-9a-z]+$/gi);
with 与
var sentence_split = arr.split(/[^0-9a-z]+/gi);
... if you prefer to go this way. ...如果您喜欢这种方式。
Explanation: the original regex was anchored (with $
) to the end of the string, and splitted by words - and not symbols separating them. 说明:原始正则表达式(用
$
)锚定在字符串的末尾,并按单词分隔-而不是用符号分隔它们。
Still, there's more than one way to do the things you do: I'd probably go just with: 尽管如此,还有多种方法可以完成您要做的事情:我可能会选择:
var words = sentence.match(/(\w+)/g);
... capturing sequences of word-consisting symbols instead of splitting the phrase by something that separates them. ...捕获包含单词的符号序列,而不是用将它们分开的方式将短语分开。 Here's a Fiddle to play with.
这是一个小提琴 。
UPDATE: And one last thing. 更新:还有最后一件事。 I felt a bit... uneasy about wasting
sort
just to get max
essentially. 我感到有点...对于仅仅为了
max
地获得max
浪费sort
感到不安。 I don't know if you share these thoughts, still here's how I would update the searching code: 我不知道您是否同意这些想法,仍然是我将如何更新搜索代码的方法:
var longest;
words.forEach(function(e) {
if (! longest || longest.length < e.length) {
longest = e;
}
});
It's forEach
, because I'm a bit lazy and imagine having a luxury of NOT working with IE8-; 这是
forEach
,因为我有点懒惰,并且可以想象不使用IE8-是一种奢侈。 still, it's quite easy to rewrite this into a regular for...
array-walking routine. 尽管如此,将其重写为常规
for...
数组遍历例程还是很容易的。
Updated fiddle . 更新小提琴 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.