0

I've the following string splitting JavaScript code:

var formula = "(field1 + field2) * (field5 % field2) / field3";
console.log(formula.split(/[+(-)% *\/]/));

And the result is out of expectation:

["", "field1", "", "", "field2", "", "", "", "", "field5", "", "", "field2", "", "", "", "field3"]

What the desired result would be:

["field1", "field2", "field5", "field2", "field3"]

I'm using Google Chrome 11 official release as the testing browser, please kindly advise what I'm doing wrong.

Thank you!

William

asked May 24, 2011 at 2:15

2 Answers 2

1

Instead of splitting on /[+(-)% *\/]/ split on more than one: /[+(-)% *\/]+/. You still might get empty matches at the start and end. To solve that problem you can use a similar regex with replace:

formula.replace(/^[+(-)% *\/]+|[+(-)% *\/]+$/g, "").split(/[+(-)% *\/]+/)

So

var formula = "(field1 + field2) * (field5 % field2) / field3";
console.log(formula.replace(/^[+(-)% *\/]+|[+(-)% *\/]+$/g, "").split(/[+(-)% *\/]+/));

yields

field1,field2,field5,field2,field3
answered May 24, 2011 at 2:20
Sign up to request clarification or add additional context in comments.

Comments

0

You are splitting at each of those characters. If you split on groups of them, you'll get your desired result.

console.log(formula.split(/[+(-)% *\/]+/));

There's just one snag: you will have to manually strip off those characters from the beginning and the end of the string (or pop off an empty string at the start/end) - it's not something you'll be able to handle by split alone.

answered May 24, 2011 at 2:20

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.