javascript - obtain slice of array from first element containing string to last element containing another -
i'm trying piece of array of strings first element contains these letters in case until lastly element containing these letters in case.
first input sentence, split whitespace. i'm trying piece indexof('in') until lastindexof('nn'), getting empty array.
here tried:
var str = "weather(nn) in(in) boston(nn)" str.split(' ').slice(str.split(' ').indexof('in'), str.split(' ').lastindexof('nn')+1); how can acquire ["in(in)", "boston(nn)"] or if string "weather(nn) in(in) boston(nn) massachusetts(nn)", ["in(in)", "boston(nn)", "massachusetts(nn)"] ?
the indexof , lastindexof methods doesn't substrings in array items, matches of finish item.
you can utilize reduce , reduceright methods seek array:
var str = "weather(nn) in(in) boston(nn)"; var arr = str.split(' '); var first = arr.reduce(function(p, c, i){ homecoming p != -1 ? p : c.indexof('in') != -1 ? : -1; }, -1); var lastly = arr.reduceright(function(p, c, i, a){ homecoming p != -1 ? p : c.indexof('nn') != -1 ? : -1; }, -1); arr = arr.slice(first, lastly + 1); demo: http://jsfiddle.net/8ws3g/
note: array.reduce , array.reduceright methods supported in ie9 , later. (the same goes array.index , array.indexof method used in question, doesn't alter requirements.)
javascript arrays
No comments:
Post a Comment