I'm having a problem in searching in an array. I wanted to check if a certain string exists in one of the elements, example
Array:
["4_1", "4_2", "4_3"]
I will check if the string "4" exists in one of the variables.
Thank you!
You could use a loop for it.
var arr = ["4_1", "4_2", "4_3"];
search = RegExp(4),
result = arr.some(search.test.bind(search));
document.write(result);
some is really good. Yes, why case insensitive on a number?The Easiest way is to use Array.prototype.join && indexOf methods
["4_1", "4_2", "4_3"].join("").indexOf("4")
Update
According to @t.niese's comment this answer may cause wrong result, for example if you are looking for 14 it will return 2 - what is wrong because your array doesnt contain element which begins on 14. In this case better to use @Nina's answer or you can join it in another way
["4_1", "4_2", "4_3"].join(" ").indexOf("14") // -1
needle , because it will then give a false positive for ["4_1", "4_2", "4_3"].join("").indexOf("14")..join it will be possible to find a failure case: ["4_1", "4_2", "4_3"].join(separator).indexOf("1"+separator+"4") will show a result. If the OP really only looks for numbers, then it will work. But because the question itself is only a generic [...]I wanted to check if a certain string exists in one of the elements[...] then under this conditions a .join will never be a good solution.
STRING.indexOf(needle)in a loop ?