In javascript, how do you search an array for a substring match -
i need search array in javascript. search part of string match string have addtional numbers assigned it. need return matched array element full string.
i.e.
var windowarray = new array ("item","thing","id-3-text","class"); i need search array element "id-" in , need pull rest of text in element (ie. "id-3-text").
thanks
in specific case, can boring old counter:
var index, value, result; (index = 0; index < windowarray.length; ++index) { value = windowarray[index]; if (value.substring(0, 3) === "id-") { // you've found it, full text in `value`. // might grab , break loop, although // having found depends on // need. result = value; break; } } // use `result` here, `undefined` if not found but if array sparse, can more efficiently properly-designed for..in loop:
var key, value, result; (key in windowarray) { if (windowarray.hasownproperty(key) && !isnan(parseint(key, 10))) { value = windowarray[key]; if (value.substring(0, 3) === "id-") { // you've found it, full text in `value`. // might grab , break loop, although // having found depends on // need. result = value; break; } } } // use `result` here, `undefined` if not found beware naive for..in loops don't have hasownproperty , !isnan(parseint(key, 10)) checks; here's why.
off-topic:
another way write
var windowarray = new array ("item","thing","id-3-text","class"); is
var windowarray = ["item","thing","id-3-text","class"]; ...which less typing you, , perhaps (this bit subjective) bit more read. 2 statements have same result: new array contents.
Comments
Post a Comment