6
\$\begingroup\$

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?

rolfl
98.1k17 gold badges219 silver badges419 bronze badges
asked May 27, 2014 at 3:12
\$\endgroup\$

1 Answer 1

6
\$\begingroup\$

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.

answered May 27, 2014 at 13:22
\$\endgroup\$
7
  • \$\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\$ Commented May 27, 2014 at 13:43
  • \$\begingroup\$ Agreed. Thats a better solution in any case :D \$\endgroup\$ Commented May 27, 2014 at 13:45
  • \$\begingroup\$ The problem with using (and|&) is that it is captured: ["Ron & Peggy Sue ", "and", " Darin Douglass"] \$\endgroup\$ Commented May 27, 2014 at 17:27
  • 1
    \$\begingroup\$ You could try with non-capturing parens (?:and|&) and the whitespace delimiter \w. \$\endgroup\$ Commented May 27, 2014 at 18:30
  • 1
    \$\begingroup\$ \w is a word delimiter, not a whitespace delimiter, afaik. \$\endgroup\$ Commented May 29, 2014 at 3:51

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.