简体   繁体   中英

Javascript Regex to select every non-alphanumeric character AND whitespace?

I'm new to JS, tried using -

/[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. 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-; still, it's quite easy to rewrite this into a regular for... array-walking routine.

Updated fiddle .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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