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);
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
You can actually make a loop and check the indexOf
to be not -1
:
["4_1", "4_2", "4_3"].forEach(function (element, index, array) { if (element.indexOf(4) != -1) alert("Found in the element #" + index + ", at position " + element.indexOf(4)); });
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.