I have a string that is written in two formats . Either "bill - nick"
or "bill @ nick"
.I want to get the two names from the string and store them in an array.I can try the split()
function but I am looking for something dynamic no matter the divider the names have .
I would appreciate your help .
CodePudding user response:
The divider in split()
can be a regular expression. So use a regular expression that matches both -
and @
.
function split_names(string) {
return string.split(/\s*[-@]\s*/);
}
console.log(split_names("bill - nick"));
console.log(split_names("bill @ nick"));
CodePudding user response:
How about using match()
:
var input = "bill - nick"; // also works with "bill @ nick"
var names = input.match(/\w /g);
console.log(names);