1

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"]

3
  • 1
    See developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… . Alternatively: Lookaheads. Commented Aug 18, 2014 at 18:28
  • 1
    So do you want the final array to be ["-3","-6",...,"-2"] or ["-",3,"-",6,...,"-",2] ? Commented Aug 18, 2014 at 18:32
  • Sorry, I should have included that in my question. I edited the question to include the desired result. Commented Aug 18, 2014 at 19:22

2 Answers 2

1

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 -).

Sign up to request clarification or add additional context in comments.

Comments

1

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"]

1 Comment

You can use reduce on the final array to write a summing function.

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.