0

I'm trying to split out the whole words out of a string without whitespace or special characters.

So from

'(votes + downvotes) / views'

I'd like to create an array like the following

['votes', 'downvotes, 'views']

Have tried the following, but catching the parens and some whitespace. https://regex101.com/r/yX9iW8/1

2
  • Is it just the string in your example or others as well? Are numbers expected in input? If so, do you want to treat them as "words?" Commented May 27, 2016 at 18:52
  • Im splitting the numbers and operators into their own arrays with another match. Commented May 27, 2016 at 18:57

3 Answers 3

2

You could use /\w+/g as regular expression in combination with String#match

var array = '(votes + downvotes) / views'.match(/\w+/g);
console.log(array);

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

Comments

1

You can use \W+ to split on all non-word characters

'(votes + downvotes) / views'.split(/\W+/g).filter(x => x !== '');
// ["votes", "downvotes", "views"]

Or \w+ to match on all word characters

'(votes + downvotes) / views'.match(/\w+/g);
// ["votes", "downvotes", "views"]

3 Comments

Thanks Paul, this worked great. As soon as I can accept an answer I will.
An even better option would be .filter(x => x)
@RichardHamilton thought about it, decided that I wasn't so comfortable with it in a filter. If you want shorter shorthand, either Boolean or x => !!x would sit better with me [2, undefined, 1, 'a', '', false, null].filter(Boolean); // [2, 1, "a"]
0

It's very simple...

var matches = '(votes + downvotes) / views'.match(/[a-z]+/ig);

You must decide for your project what characters make a words, and min-length of word. It can be chars with digits and dash with min-length of 3 characters...

[a-z0-9-]{3,}

Good luck!

Comments

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.