Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to not separate on dash/hyphen when using lodash _.words?

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?

like image 936
reedog117 Avatar asked May 15 '15 19:05

reedog117


People also ask

How do you use dashes and hyphens?

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 (—).

Whats the difference between a hyphen and a 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.


2 Answers

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)

like image 147
emartinelli Avatar answered Nov 07 '22 08:11

emartinelli


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

like image 20
Pedro Lobito Avatar answered Nov 07 '22 10:11

Pedro Lobito