With regex a simple example would be to use .split
with the meta-character \b
:
var names = ' GEO X GEO3 X GEO4 X';
var nameList = names.trim().split(/\b[\sX]+\b/i).filter(function (value) {
return value;
});
console.log(nameList);
As in the example of @dvd I also used trim
, but I used it previously, since +
in regex already "eliminates" spaces between words and I used .filter
, being an empty string .filter
will already consider as false
and will filter it the result that comes after the last X
of:
GEO X GEO3 X GEO4 X
That would be an empty string in the case.
Explaining the regex
\b
is a meta-character that is used to find a match at the beginning or end of a word, thus preventing words that have the letter X
in the middle from being divided as well
Anything within [
and ]
in regex will be considered acceptable to split the string
The sign of +
is used so that the previous regex expression is used to match everything that matches, until you find something that does not "case".
Important detail, flag
g
is not required when used with .split
, then this .split(/\sx|x\s/gi)
will have the same as .split(/\sx|x\s/i)