I have the following 2 string which I supposed to split according to delimiter: '/' or "/*"
my code:
var move = "1/2/13/14";
var results = move.split(new RegExp("[/\*?]"));
results are GOOD:
["1","2","13","14"]
BUT, for the next example:
var move = "1/*2/13/*14";
var results = move.split(new RegExp("[/\*?]"));
I get BAD results:
["1","","2","13","","14"]
Why?? How can I modify it to work correctly?
Thank you!
-
What do you expect the outcome to be? Just like the first?epascarello– epascarello2015年02月05日 17:24:30 +00:00Commented Feb 5, 2015 at 17:24
4 Answers 4
You can just make * optional after /:
"1/*2/13/*14".split( /\/\*?/ );
["1", "2", "13", "14"]
"1/2/13/14".split( /\/\*?/ );
["1", "2", "13", "14"]
Comments
By using [], you are creating a character class, which means "any one of these symbols". This means your regex is looking for the literal characters /, * (needlessly escaped in char class), or ? for splitting. The * and ? do not take on their meta functionality inside the character class.
The regex you'll want is /\/\*?/ (as a regex literal), or with the constructor new RegExp("/\\*?"). You do not need the character class.
Comments
You are having problems because you are grouping the characters with the brackets .[ and ]). In a regular expression, those characters will allow any of the characters within the group to be matched.
If you remove them like this: var results = move.split(new RegExp("/\\*?"));, you should get the results that you want.
Comments
This one helps:
move.split(new RegExp("[/][*]?"));
1 Comment
\ in the character class with * would have no impact, as it is interpreted as the escape symbol. it would take a double backslash to cause trouble ( move.split(/[/][\\*]?/); nb: the RegExp constructor takes a string as its argument, thus a double escape would apply, thus it takes new RegExp("[/][\\\\*]?") to fail). Anyway, you are perfectly right that the escaping inside the character class is superfluous.