I am using lodash to split up usernames that are fed to me in a string with some sort of arbitrary separator. I would like to use _.words() to split strings up into words, except for hyphens, as some of the user names contain hyphens.
Example:
_.words(['user1,user2,user3-adm'], RegExp)
I want it to yield:
['user1', 'user2', 'user3-adm']
not this (_.words(array) without any pattern):
['user1', 'user2', 'user3', 'adm']
What is the right String/RegExp to use to make this happen?
The initial case can be solved by this:
_.words(['user1,user2,user3-adm'], /[^,]+/g);
Result:
["user1", "user2", "user3-adm"]
[EDITED]
If you want to add more separators, add like this:
_.words(['user1,user2,user3-adm.user4;user5 user7'], /[^,.\s;]+/g);
Result:
["user1", "user2", "user3-adm", "user4", "user5", "user7"]
Last snippet will separate by:
commas (,
),
dots (.
),
spaces (\s
),
semicolons (;
)
Alternatively you can use:
_.words(['user1,user2,user3-adm.user4;user5 user7*user8'], /[-\w]+/g)
Result:
["user1", "user2", "user3-adm", "user4", "user5", "user7", "user8"]
In this case you can add what you don't want as delimiter. Here it will will be separated by every character which is not \w
(same as [_a-zA-Z0-9]
) or -
(dash)