我有一个像"abc('x','y','zzz')"
这样的字符串,我希望得到一个包含“x”,“y”和“zzz”的字符串数组(即'
之间的字符串(单引号)) 。我必须在javascript中执行此操作。
使用substring方法做起来并不容易。我希望得到一个方法,它从传递的字符串中返回' (single quote)
之间的字符数组。
答案 0 :(得分:1)
您可以执行以下操作:
var input = "abc('x','y','zzz')";
input = input.match(/\w+/g); // ["abc", "x", "y", "zzz"]
input = input ? input.slice(1) : []; // ["x", "y", "zzz"]
input = input.length > 1
? input.slice(0, -1).join(', ') + ' and ' + input.pop()
: input[0] || '';
// "x, y and zzz"
包含内部功能:
// string -> array
function split(input) {
input = input.match(/\w+/g);
return input ? input.slice(1) : [];
}
// array -> string
function format(input) {
return input.length > 1
? input.slice(0, -1).join(', ') + ' and ' + input.pop()
: input[0] || '';
}
format(split("abc('x','y','zzz')")); // ["x", "y", "zzz"] -> "x, y and zzz"
format(split("abc('x','y')")); // ["x", "y"] -> "x and y"
format(split("abc()")); // [] -> ""
答案 1 :(得分:1)
如果只有一个这样的匹配,那么:
"abc('x','y','zzz')".replace(/^[^\(]*\(|\).*$/g,'').match(/\w+/g); // ['x','y','zzz']
会做的。
答案 2 :(得分:1)
我更喜欢这个简单任务的纯正则表达式解决方案,而不是组合几个字符串操作:
var input = "abc('x','y','zzz')";
input.match(/(?!')(\w+)(?=')/g) // ["x", "y", "zzz"]
答案 3 :(得分:0)
试试这个:
var str = "abc('x','y','zzz')";
// remove string before (
str = str.replace(str.slice(0, str.indexOf('(') + 1),'');
// remove the last )
str = str.substr(0,str.length - 1);
现在你有一个字符串'x','y','zzz'。如果你想制作一个数组,试试这个:
var strArray = str.split(',');
这是jsfiddle