Wige
Wige

Reputation: 3918

javascript: split a string into an array with different delimiters

I have an arithmetic string that I want to parse to get the result. The best idea I have come up with so far is to convert the string to an array, but I am not sure what the correct (and cross compatible) way to do this is.

The string I have to parse is "-3-6-9-3+10-3-5-2" (D&D damage rolls and resistance for an initiative tracker). To get a usable array, I need to split this by the operator of + or -, but not lose the operator since I need to know which operation to perform.

Is there a way to do this in JavaScript?

This is the array I hope to get back: ["-3","-6","-9","-3","+10","-3","-5","-2"]

Upvotes: 1

Views: 73

Answers (2)

ckersch
ckersch

Reputation: 7687

You can split an rejoin, adding a different delimiter to use for a final split by both:

var x = '-3-6-9-3+10-3-5-2';
var y = x.split('-').join(';-;').split('+').join(';+;').split(';');
//["", "-", "3", "-", "6", "-", "9", "-", "3", ...]

y is an array which splits the original string on the - and + characters, but then adds them back into the array in their original places.

If you want to keep the + and - characters with their characters, remove the second ; from the joins.

var y = x.split('-').join(';-').split('+').join(';+').split(';');
//["", "-3", "-6", "-9", "-3", "+10", "-3", "-5", "-2"]

Upvotes: 1

raina77ow
raina77ow

Reputation: 106483

While using capturing parens is certainly a valid approach, I'd recommend using lookahead split:

var str = '-3-6-9-3+10-3-5-2';
str.split(/(?=[-+])/); // no need to check for digits here actually
// ["-3", "-6", "-9", "-3", "+10", "-3", "-5", "-2"]

In this case, each split point will be placed before the sign (i.e., + or -).

Upvotes: 1

Related Questions