Sagar Chaudhary
Sagar Chaudhary

Reputation: 1403

Parse dynamic string in javascript

I have a string like this :

var str = "[x] + [y] - [z]"

I want an array: arr[0] = x , arr[1]=y ...and so on.

My string can contain multiple operators and fields

Upvotes: 0

Views: 276

Answers (1)

Ishwar Patil
Ishwar Patil

Reputation: 1736

You can write a regex to replace the arithmatic operations and '['. Then split the string by ']' to get an array.

PS: slice(0, -1) is remove the last item from the array which is just a "".

 var str = "[x] + [y] - [z]";
 
var arr = str.replace(/[+-/*//[ ]/g,'').split("]").slice(0, -1);;

console.log(arr)

Upvotes: 2

Related Questions