1

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?

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

5 Answers 5

2

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".

Sign up to request clarification or add additional context in comments.

2 Comments

performance-wise, is it better, equal, or worse than all the split answers ?
@Stephane I don't think there's a significant difference in performance between the two; I personally find matching easier to reason with than splitting on the negative expression.
0
[^a-z]+

You can split by this to get the desired result.

Comments

0

try: var words = itemObject["name"].toLowerCase().split(/([^a-z]+)/);

Comments

0

Working:

var words = itemObject["name"].match(/[a-z]+/ig);

Output:

hello,you,hey,foo

Comments

0

I'd suggest:

var matches = "hello3you ?! hey 32 foo!".split(/[^a-z]+/).filter(function(el) {
  if (el.length) {
    return el;
  }
});

console.log(matches);

  • [^a-z] is a range of characters that are not a-z (inclusive),
  • + requires a match of one, or more, of those characters.

3 Comments

If you have a string like "hello!" this would yield an array with two elements, the last one being an empty string.
That's a good point; and suddenly I'm seeing why match() is the better option. I may, however, have added a slightly complex means of dealing with that.
This is where PHP's preg_split() has a slight advantage because it allows for a flag to skip empty segments :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.