0

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

4
  • What is your ultimate aim by parsing the string to array? Commented Mar 8, 2018 at 7:06
  • @Rajesh, have you read 'Be nice' policy?? Probably he's just trying something out. Sarcasm wouldnt help Commented Mar 8, 2018 at 7:43
  • 1
    @Rajesh, how can you be sure that he didnt try or research at first? May be he was just stuck. happens to all. can you find a duplicate question somewhere? Commented Mar 9, 2018 at 5:59
  • Please be more descriptive. Try to provide your code. Commented Mar 13, 2018 at 14:32

1 Answer 1

2

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)

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

5 Comments

i have a string like this "[numA1-E1]+[SalineLotNumberQ2-P1]" . The regex gives arr[0] = numA1E1 whereas i want arr[0] = numA1-E1. If you can help out on this?
Please create an new question.
Cant create that. It will be the same question. I just want the minus sign to be not removed when it is in a [ ].
I have posted a new question. Please give the answer. stackoverflow.com/questions/49190853/…
Check my answer on the new question: stackoverflow.com/a/49191768/6654503

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.