Pattern on .words() - Lodash

Hi.

I’m trying to understand how I can set a pattern for method .words() on Lodash.

They put an example like this:
_.words('fred, barney, & pebbles', /[^, ]+/g); // => ['fred', 'barney', '&', 'pebbles']

How can I understand this pattern /[^, ]+/g ?

Thanks.

Hi there.

That pattern is called a regular expression.

They can be quite complicated, but if you’d like to learn more about them you can find more information here on the Mozilla Dev Network.

2 Likes

/[^, ]+/g

Breaking it down…

/.../    =>  pattern delimiters

[...]    =>  character class

[^...]   =>  ^ indicates NOT

[^, ]    =>  matches single characters not in the string

/[..]+/  =>  matches one or more

/.../g   =>  global flag, search entire string for all matches

Note the returned values array,

['fred', 'barney', '&', 'pebbles']

Commas and space characters are gone.

Found this very useful utility for checking your patterns…

https://regex101.com/

2 Likes

Another quick aside…

If all we want are words, and nothing else, we can use this pattern…

/[^\W]+/g
1 - _.words() is defined - Passed!
2 - Returns an array - Passed!
3 - Returns an array of words from a string with one word - Passed!
4 - Returns an array of words from a string with two words - Passed!
5 - Returns an array of words from a string with three words - Passed!
2 Likes

Thanks for the link, I’m going to read it. :ok_hand:t4:

1 Like

Thanks for breaking it down, it’s helping me a lot.

2 Likes