简体   繁体   中英

Need a regular expression to split string in javascript

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.

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' 

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM