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"]
Try this, no regex:
var arr = str.split(' - ')
Edit
Multiple separators:
var arr = str.split(/ [-*+,] /)
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 AZ, 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! :-)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.