Reputation: 4696
In JavaScript, how would I get ['John Smith', 'Jane Doe']
from "John Smith - Jane Doe"
where -
can be any separator (\ / , + * : ;
) and so on, using regex ?
Using new RegExp('[a-zA-Z]+[^\/|\-|\*|\+]', 'g')
will just give me ["John ", "Smith ", "Jane ", "Doe"]
Upvotes: 1
Views: 155
Reputation: 1074335
If you want to match multiple words, you need to have a space in your character class. I'd think something like /[ a-zA-Z]+/g
would be a starting point, used repeatedly with exec
or via String#match
, like this: Live copy | source
var str = "John Smith - Jane Doe";
var index;
var matches = str.match(/[ a-zA-Z]+/g);
if (matches) {
display("Found " + matches.length + ":");
for (index = 0; index < matches.length; ++index) {
display("[" + index + "]: " + matches[index]);
}
}
else {
display("No matches found");
}
But it's very limited, a huge number of names have characters other than A-Z, you may want to invert your logic and use a negated class (/[^...]/g
, where ...
is a list of possible delimiter characters). You don't want to leave "Elizabeth Peña" or "Gerard 't Hooft" out in the cold! :-)
Upvotes: 1
Reputation: 94101
Try this, no regex:
var arr = str.split(' - ')
Edit
Multiple separators:
var arr = str.split(/ [-*+,] /)
Upvotes: 2