[英]Javascript regex to split on either ' & ', ' - ' or ' > '
I have a string like this: 我有一个像这样的字符串:
var category = 'New & improved > crazy - whatever'
I'd like to convert it to: 我想将其转换为:
var arr = ['New', 'improved', 'crazy', 'whatever']
Should work with any combination of ' & ', ' - ' or ' > '
(spaces included). 应该与' & ', ' - ' or ' > '
任意组合一起使用(包括空格)。
So far I'm doing: 到目前为止,我正在做:
var arr = [];
if(obj.categories[i].name.indexOf(" > ") >= 0){
var arr2 = obj.categories[i].name.split(" > ");
for(var i = 0; i<arr.length; i++){
if (arr[i].indexOf(' & ') >=0){
var newarr = arr[i].split(' & ');
arr.push(newarr);
}else{
arr.push(arr[i]);
}
}
}
if(obj.categories[i].name.indexOf(" - ") >= 0){
var arr2 = obj.categories[i].name.split(" - ");
for(var i = 0; i<arr.length; i++){
if (arr[i].indexOf(' & ') >=0){
var newarr = arr[i].split(' & ');
arr.push(newarr);
}else{
arr.push(arr[i]);
}
}
}else if(obj.categories[i].name.indexOf(" & ") >= 0){
var arr = obj.categories[i].name.split(" & ");
return arr;
}else{
return [obj.categories[i].name];
}
but this doesn't work if there are both ampersands and dashes in the string. 但是,如果字符串中同时包含“&”和破折号,则此方法将无效。 I feel like a regex could handle this much better anyhow, what's the best way to achieve this and make it relatively-futureproof for different use-cases (only involving the above separators, of course)? 我觉得正则表达式无论如何都可以更好地解决这个问题,实现此目标并使其针对不同用例(相对于将来,当然仅涉及上述分隔符)相对未来的最佳方法是什么?
var category = 'New & improved > crazy - whatever';
category.split(/\s*[-&>]\s*/); // => ["New", "improved", "crazy", "whatever"]
NOTE: -
should not be in the middle. 注意: -
不应在中间。 Otherwise it is interpreted as character range. 否则,它将被解释为字符范围。
Try: 尝试:
'New & improved > crazy - whatever'.split(/[>&-]/);
or without spaces in the result (but result may depend on the formatting of the initial string): 或结果中没有空格(但结果可能取决于初始字符串的格式):
'New & improved > crazy - whatever'.split(/\\s+[>&-]\\s+/);
You can use this: 您可以使用此:
var result = yourstring.split(/[\s>&-]+/);
print(result);
var category = 'New & improved > crazy - whatever'
var arr = category.split(/[\&\>\-]/);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.