sri_84
sri_84

Reputation: 91

Is there a javascript method to find substring in an array of strings?

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 does not work:

var array= ["abcdefg", "hijklmnop"];
console.log(array.indexOf("mnop")); //-1 since it does not find it in the string

Upvotes: 0

Views: 873

Answers (5)

gcampbell
gcampbell

Reputation: 1272

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.

Upvotes: 1

Adam Buchanan Smith
Adam Buchanan Smith

Reputation: 9449

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>

Upvotes: 0

maioman
maioman

Reputation: 18744

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)

Upvotes: 1

CoconutFred
CoconutFred

Reputation: 454

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");
});

Upvotes: 0

Shawn K
Shawn K

Reputation: 778

var array= ["abcdefg", "hijklmnop"];
var newArray = array.filter(function(val) {
    return val.indexOf("mnop") !== -1
})
console.log(newArray)

Upvotes: 3

Related Questions