Suppose my array is [\"abcdefg\", \"hijklmnop\"] and I am looking at if \"mnop\" is part of this array. How can I do this using a javascript method?
I tried this and it
var array= ["abcdefg", "hijklmnop"];
var newArray = array.filter(function(val) {
return val.indexOf("mnop") !== -1
})
console.log(newArray)
a possible solution is filtering the array through string.match
var array= ["abcdefg", "hijklmnop"];
var res = array.filter(x => x.match(/mnop/));
console.log(res)
You can use Array#some:
// ES2016
array.some(x => x.includes(testString));
// ES5
array.some(function (x) {
return x.indexOf(testString) !== -1;
});
Note: arrow functions are part of ES6/ES2015; String#includes is part of ES2016.
The Array#some
method executes a function against each item in the array: if the function returns a truthy value for at least one item, then Array#some
returns true.
Can be done like this https://jsfiddle.net/uft4vaoc/4/
Ultimately, you can do it a thousand different ways. Almost all answers above and below will work.
<script>
var n;
var str;
var array= ["abcdefg", "hijklmnop"];
//console.log(array.indexOf("mnop")); //-1 since it does not find it in the string
for (i = 0; i < array.length; i++) {
str = array[i];
n = str.includes("mnop");
if(n === true){alert("this string "+str+" conatians mnop");}
}
</script>
Javascript does not provide what you're asking before because it's easily done with existing functions. You should iterate through each array element individually and call indexOf
on each element:
array.forEach(function(str){
if(str.indexOf("mnop") !== -1) return str.indexOf("mnop");
});