1

I need some help with regular expressions in javascript. I've got a string like:

var S = '["abc","defg", "hij"]';

How could I split it in javascript to get a[0]=abc, a[1]=defg, a[2]=hij? Because var a = S.split(','); just give me a[0]=["abc" and so on. Thank you very much.

2
  • Learn to use quotes properly, It would be better if you define your string as var s = '["abc","defg", "hij"]'; Commented Jul 20, 2016 at 12:43
  • 1
    I don't see how the above code line works? there are unescaped quotes in the string... please edit. Commented Jul 20, 2016 at 12:44

2 Answers 2

3

If you fix the quotes you use to delimit the string, then you can JSON.parse the string to an array and work with it as you need, like this:

var s = '["abc","defg", "hij"]';
var arr = JSON.parse(s);

console.log(arr);
console.log(arr[0]); // = 'abc'

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

1 Comment

Thank you very much, that's it
0

If you mean:

var S = ["abc", "def", "ghi"];

Then use S[0], S[1] and S[2].

If you mean:

var S = "[\"abc\", \"def\", \"ghi\"]";

Then use JSON parser

Complete example:

var S = "[\"abc\", \"def\", \"ghi\"]";
var SParsed = JSON.parse(S);
alert(SParsed [1]); //def

Comments

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.