patternjavascriptMinor
Combining two indexOf and regex in to one
Viewed 0 times
indexofcombiningtwooneandregex
Problem
I have the following code that splits a combination of names on either the word
Its returns an array of names like:
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?
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` separatorI 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?
Solution
You were almost there. You can use pipe (
EDIT: The syntax
Also, there is no need to check for either delimiter in
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.Code Snippets
var name = 'Ron & Peggy Sue and Darin Douglass';
names = name.split(/\s(?:and|&)\s/ig);Context
StackExchange Code Review Q#51800, answer score: 6
Revisions (0)
No revisions yet.