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 @dvd example I also used the trim
, but I used it previously, since +
in regex already "eliminates" the spaces between words and I used .filter
, being an empty string .filter
will already consider how false
and it will filter out the result that comes after the last X
of:
GEO X GEO3 X GEO4 X
In this case it would be an empty string.
Explaining the regex
The \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 be divided also
Anything inside of [
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 anything that matches, until you find something that does not "marry".
Important detail, the flag
g
is not necessary when used with .split
, so this .split(/\sx|x\s/gi)
will have the same as .split(/\sx|x\s/i)
It would be nice to have an example of the expected output.
– Jéf Bueno
That one
$
before the\s
seems kind of wrong to me.– Guilherme Nascimento