I have the following code that splits a combination of names on either the word and
or the &
ampersand:
var name = 'Ron & Peggy Sue'; //or 'Ron and Peggy Sue';
if ( name.indexOf('&') > -1 ){
names = name.split(/ & /g);
}
if ( name.toLowerCase().indexOf(' and ') > -1 ) {
names = name.split(/ and /gi);
}
Its returns an array of names like:
names = ['Ron', 'Peggy Sue']; //regardless of `&` or `and` separator
I was trying to combine these two conditions into one, but the results were not what I wanted. I know there must be a better way. How can the above code be improved?
1 Answer 1
You were almost there. You can use pipe (a|b
) to designate the regex to look for both a
and b
. With that knowledge your split is as easy as:
var name = 'Ron & Peggy Sue and Darin Douglass';
names = name.split(/\s(?:and|&)\s/ig);
EDIT: The syntax (?:...)
is whats called non-capturing parens. These match the regex provided as '...' but it does not remember the matches. The problem with the simple /\s(and|&)\s/ig/
was that the words and
and &
would be matched. This new syntax 'matches' them but does not remember (i.e. report) them. Thanks to @cbojar for the pointer.
Also, there is no need to check for either delimiter in name
. If none exist it will simply return a single-element array with name
as its element.
-
\$\begingroup\$ Totally nit-picking, but rather than repeat the spaces surrounding the two words, I'd say
/ (and|&) /ig
- or/\b(and|&)\b/ig
\$\endgroup\$Flambino– Flambino2014年05月27日 13:43:26 +00:00Commented May 27, 2014 at 13:43 -
\$\begingroup\$ Agreed. Thats a better solution in any case :D \$\endgroup\$BeetDemGuise– BeetDemGuise2014年05月27日 13:45:58 +00:00Commented May 27, 2014 at 13:45
-
\$\begingroup\$ The problem with using
(and|&)
is that it is captured:["Ron & Peggy Sue ", "and", " Darin Douglass"]
\$\endgroup\$chovy– chovy2014年05月27日 17:27:48 +00:00Commented May 27, 2014 at 17:27 -
1\$\begingroup\$ You could try with non-capturing parens
(?:and|&)
and the whitespace delimiter\w
. \$\endgroup\$cbojar– cbojar2014年05月27日 18:30:51 +00:00Commented May 27, 2014 at 18:30 -
1\$\begingroup\$
\w
is a word delimiter, not a whitespace delimiter, afaik. \$\endgroup\$chovy– chovy2014年05月29日 03:51:42 +00:00Commented May 29, 2014 at 3:51