各位,我看过underscore.string和string.js模块,但仍然找不到一种很好的方法来执行以下操作:
假设我有一个查询字符串:
"!dogs,cats,horses!cows!fish"我想将它传递给一个函数,该函数查找以!开头的所有单词,并返回一个数组:
['dogs','cows','fish']类似地,同一个函数应该返回一个以,开头的单词数组。
['cats','horses]谢谢!
发布于 2015-03-11 20:26:49
您可以使用RegEx轻松匹配拆分字符。
var string = "!dogs,cats,horses!cows!fish";
var splitString = string.split(/!|,/);
// ["dogs", "cats", "horses", "cows", "fish"]唯一的问题是,如果您用!启动该数组,它可能会在数组的开头添加一个空字符串。您可以通过一个函数来修复这个问题:
splitString.forEach(function(item){
if(item === ""){
splitString.splice(splitString.indexOf(item), 1)
}
});编辑
作为对你的澄清的回应,这里有一个你要求的函数。它当前返回一个值为commas和exclaim的对象,每个对象都带有相应元素的数组。
function splitString(str){
var exclaimValues = [];
var expandedValues = [];
var commaValues = [];
var needsUnshift = false;
//First split the comma delimited values
var stringFragments = str.split(',');
//Iterate through them and see if they contain !
for(var i = 0; i < stringFragments.length; i++){
var stringValue = stringFragments[i];
// if the value contains an !, its an exclaimValue
if (stringValue.indexOf('!') !== -1){
exclaimValues.push(stringValue);
}
// otherwise, it's a comma value
else {
commaValues.push(stringValue);
}
}
// iterate through each exclaim value
for(var i = 0; i < exclaimValues.length; i++){
var exclaimValue = exclaimValues[i];
var expandedExclaimValues = exclaimValue.split('!');
//we know that if it doesn't start with !, the
// the first value is actually a comma value. So move it
if(exclaimValue.indexOf('!') !== 0) commaValues.unshift(expandedExclaimValues.shift());
for(var j = 0; j < expandedExclaimValues.length; j++){
var expandedExclaimValue = expandedExclaimValues[j];
//If it's not a blank entry, push it to our results list.
if(expandedExclaimValue !== "") expandedValues.push(expandedExclaimValue);
}
}
return {comma: commaValues, exclaim: expandedValues};
}因此,如果我们这样做:
var str = "!dogs,cats,horses!cows!fish,comma!exclaim,comma2,comma3!exclaim2";
var results = splitString(str)results将是:
{
comma: ["comma3", "comma", "horses", "cats", "comma2"],
exclaim: ["dogs", "cows", "fish", "exclaim", "exclaim2"]
} https://stackoverflow.com/questions/28996583
复制相似问题