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?

\$\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.

\$\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\$
    – Flambino
    May 27, 2014 at 13:43
  • \$\begingroup\$ Agreed. Thats a better solution in any case :D \$\endgroup\$ 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
    May 27, 2014 at 17:27
  • 1
    \$\begingroup\$ You could try with non-capturing parens (?:and|&) and the whitespace delimiter \w. \$\endgroup\$
    – cbojar
    May 27, 2014 at 18:30
  • 1
    \$\begingroup\$ \w is a word delimiter, not a whitespace delimiter, afaik. \$\endgroup\$
    – chovy
    May 29, 2014 at 3:51

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.