How to convert string and operation chars to array?

let myInput = 2-5+(3*2)
How can we convert it to myinputArray = [ "2", "-", "5", "+", "(", "3", "x", "2", ")" ]

What have you tried? Have you looked at the split() method?

Yes I have tried the split method using regex I found searching online.

myInput.split( / ( [ * \ / + - ] ) / ) gives me [ ‘2’, ‘-’, ‘5’, ‘+’, ‘(3’, '*x, ‘2)’ ]. It won’t separate the parenthesis.

Why jam a condition in there? If you want to split everything, then split everything, like the second example in the documentation:

If separator is an empty string ( "" ), str is converted to an array of each of its UTF-16 “characters”.

Yes but the separator here is the operators …the + , - , / , x , and the culprit parenthesis ( ). It would have been easier if the separator was an empty string

I don’t understand the problem.

let myInput = "2-5+(3*2)";
let myResult = myInput.split('');
console.log(myResult); // [ "2", "-", "5", "+", "(", "3", "*", "2", ")" ]

Back at it again. Your solution is good but only works for single digits.
Try let myInput = '40-(60*2)' ; let myResult = myInput.split( ' ' ); console.log(myResult) ; // [ '4', '0', '-', '(', '6', '0', '*', '2', ')' ]
The desired result was [ ‘40’, ‘-’, ‘(’, ‘60’, ‘*’, ‘2’, ‘)’ ]

Have you done this:

specifically this one:

That is a regex tutorial :smile: Yes I know I will have to take a regex lesson but for the time being , a solution would be great.

We aren’t soda pop machines of code unfortunately. We don’t write solutions for users. The one specific regex lesson I pointed you to I think is what you’re looking for. You want to match on specific characters.

Hmm, perhaps not though, as split strips out the separators. You can always manually parse with a loop.

I have spent on many hours trying to get the solution. As I referred earlier , I found a regex that worked for the operators (except for the parenthesis) . I read that getting a parenthesis in regex is VERY HARD. But If I have to teach myself, I will try.

You can do this without regex by using a for loop.

:wink:

let myResult = myInput.match(/[()*\/+-]|\d+/g); 

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.