通过几个分隔符将字符串拆分为数组

时间:2015-03-11 20:22:42

标签: javascript arrays

民间,   我查看了underscore.string和string.js模块,但仍无法找到执行以下操作的好方法:

假设我有一个查询字符串字符串:

"!dogs,cats,horses!cows!fish"

我想将它传递给一个函数,该函数查找以!开头的所有单词,然后返回一个数组:

['dogs','cows','fish']

同样,相同的函数应返回以,开头的单词数组:

['cats','horses]

感谢!!!

1 个答案:

答案 0 :(得分:1)

您可以使用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)
    } 
  });

修改

在回应你的澄清时,这里有一个功能就像你问的那样。它当前返回一个值为commasexclaim的对象,每个对象都包含相应元素的数组。

JSBin showing it working.

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"]
}