简体   繁体   English

需要一个正则表达式来在javascript中拆分字符串

[英]Need a regular expression to split string in javascript

I need some help with regular expressions in javascript. 我需要一些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 ? 我怎么能在javascript中拆分它来得到a[0]=abca[1]=defga[2]=hij Because var a = S.split(','); 因为var a = S.split(','); just give me a[0]=["abc" and so on. 给我a[0]=["abc"等等。 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: 如果您修复了用于分隔字符串的引号,那么您可以将字符串JSON.parse转换为数组并根据需要使用它,如下所示:

 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]. 然后使用S[0], S[1] and S[2].

If you mean: 如果你的意思是:

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

Then use JSON parser 然后使用JSON解析器

Complete example: 完整的例子:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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