Javascript Split Array -


i trying write custom string splitting function, , harder have expected.

basically, pass in string , array of values string split on, , return array of substrings, removing empty ones , including values splits on. if string can split @ same place 2 different values, longer 1 has precedence.

that is,

split("go ye away, want peace && quiet. & thanks.", ["go ", ",", "&&", "&", "."]); 

should return

["go ", "ye away", ",", " want peace ", "&&", " quiet", ".", " ", "&", " thanks", "."] 

can think of reasonably simple algorithm this? if there built-in way in javascript (i don't think there is), nicer.

something this?

function mysplit(input, delimiters) {      // sort delimiters array length avoid ambiguity     delimiters.sort(function(a, b) {        if (a.length > b.length) { return -1; }        return 0;     }      var result = [];      // examine input 1 character @ time     (var = 0; < input.length; i++) {         (var j = 0; j < delimiters.length; j++) {             if (input.substr(i, delimiters[j].length) == delimiters[j]) {                  // add first chunk of input result                 if (i > 0) {                     result.push(input.substr(0, i));                 }                 result.push(delimiters[j]);                  // reset input , iteration                 input = input.substr(i + delimiters[j].length);                 = 0;                 j = 0;             }         }     }      return result; }  var input      = "go ye away, want peace && quiet. & thanks."; var delimiters = ["go ", ",", "&&", "&", "."];  console.log(mysplit(input, delimiters)); // output: ["go ", "ye away", ",", " want peace ", //          "&&", " quiet", ".", " ", "&", " thanks", "."] 

Comments

Popular posts from this blog

linux - Using a Cron Job to check if my mod_wsgi / apache server is running and restart -

actionscript 3 - TweenLite does not work with object -

jQuery Ajax Render Fragments OR Whole Page -