0

I have a string

var str = '[SYSTEM, Test, check]'

I want to convert this String into array in order to access these values separately., like..

var array = ['SYSTEM', 'Test', 'check'];
1
  • 4
    I assume that you mean var str = '[SYSTEM, Test, check]'? Commented Jan 14, 2014 at 12:15

2 Answers 2

6

You can do that by removing the beginning and end brackets and then splitting the string by ', '.

var array = str.replace(/\[|\]/g,'').split(', ');

This uses a regex to remove the brackets and than the split method to make the array

To elaborate a little more... I use /[|]/ to look for instances of [ and ]. I flag the regex as global (the g) in order to find all instances of it. Then I replace the instances with an empty string. Once all the instances have been removed, I split the string into an array based off of a comma and space seperator ', '

UPDATE:

As per the comments, you should check for the brackets at the beginning and end of the string, since we will assume you want brackets from any other values.

var array = str.replace(/(^\[|\]$)/g, '').split(', ');
5
  • 1
    This will remove [ and ] from array values as well... jsfiddle.net/T886K Commented Jan 14, 2014 at 12:18
  • 1
    I would even use anchors to avoid replacing brackets inside strings: /^\[|\]$/ Commented Jan 14, 2014 at 12:19
  • 2
    Nice, but that's better to check if brackets are the first and last characters : str.replace(/^\[|\]$/g,'').split(', '). EDIT : I edited your answer (editception :) ). Commented Jan 14, 2014 at 12:20
  • Actually I don't know anything about Regular Exps or what else is this , so can you please explain a little or just give an external link to study about this.. Commented Jan 14, 2014 at 12:26
  • 1
    @AnkitLamba developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/… would be helpful to look at. I tried to explain some in the paragraph right about "UPDATE" Commented Jan 14, 2014 at 12:31
4
var array = str.substring(1, str.length - 1).split(", ");

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.