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?
A hyphen (-) is a punctuation mark that's used to join words or parts of words. It's not interchangeable with other types of dashes. A dash is longer than a hyphen and is commonly used to indicate a range or a pause. The most common types of dashes are the en dash (–) and the em dash (—).
A hyphen joins two or more words together while a dash separates words into parenthetical statements. The two are sometimes confused because they look so similar, but their usage is different. Hyphens are not separated by spaces, while a dash has a space on either side.
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)
words
accept a regex expression to match the words and not to split them, being so, just use a regex that matches everything besides a comma, i.e.:
_.words(['user1,user2,user3-adm'], /[^,]+/g);
Alternatively, you can use split
.
result = wordlist.split(/,/);
https://lodash.com/docs#words
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With