0

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!

1
  • What do you expect the outcome to be? Just like the first? Commented Feb 5, 2015 at 17:24

4 Answers 4

3

You can just make * optional after /:

"1/*2/13/*14".split( /\/\*?/ );
["1", "2", "13", "14"]

"1/2/13/14".split( /\/\*?/ );
["1", "2", "13", "14"]
Sign up to request clarification or add additional context in comments.

Comments

2

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

1

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

0

This one helps:

move.split(new RegExp("[/][*]?"));

1 Comment

@eldarerathis just for the record, a single \ 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.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.