Skip to content

re: Is there a way to get the value that's between 2 given characters in JavaScript? VIEW POST


You can use Regular Expressions to find a string between two brackets but I'm not sure this gives you enough information.

In the interests of giving you a direct answer to your problem - perhaps you could loop over each character in the string and every time you reach an open bracket, you increment a depth counter.

By doing a pass, you'll find the greatest depth of nested brackets (i.e. "3 + (2 * (7 + 8))" would have a depth of 2.

Then you do another pass, counting the number of open brackets with a counter variable. When you reach a closing one, you check the value of the counter variable and if it equals the depth, you calculate the value of that bracket, replacing the brackets and everything between with the value obtained (you can do this easily by storing and retrieving the position of the opening bracket and then replacing chars from that index to the current position).

Finally by subtracting 1 from depth and repeating the previous paragraph until depth is 0 you will have ensured that all brackets are evaluated in order.

code of conduct - report abuse