How to find element of array that is string contains a value in array in javascript
#element of array that is string contains a value in array in javascript #javascript #coding #program in javascript
Here we see Example of finding array element in String .So basically there is two method to find Array value in String
Introduction
Finding whether a string contains a value from an array is a common task in JavaScript. There are multiple ways to check if an array contains a specific value or if any element in an array matches a substring in a given string.
In this guide, we will explore two approaches:
JavaScript provides the indexOf()
method to check if a value exists in an array. This method returns the index of the value if found, otherwise it returns -1
.
var myarr = ['java', 'python', 'scala', 'nodejs', 'bigdata', 'hive', 'sql', 'HTML'];
var arrayContainsValue = (myarr.indexOf("turtles") > -1);
console.log(arrayContainsValue); // Output: false
indexOf()
method searches for the element "turtles" in the array myarr
.-1
, meaning the element is not present in the array.
If we need to check whether a string contains any value from an array, we can use the some()
method along with the includes()
method.
function getKeyWord() {
var language = "null";
const str = "I am a learner of HTML";
const arr = ['java', 'python', 'scala', 'nodejs', 'bigdata', 'hive', 'sql', 'HTML'];
const contains = arr.some(element => {
if (str.includes(element)) {
language = element;
return true;
}
return false;
});
return language;
}
console.log(getKeyWord()); // Output: "HTML"
getKeyWord()
initializes a language
variable to "null".some()
method iterates over the array and checks if str.includes(element)
.language
is updated with the matching element.indexOf()
to check for an exact value in an array.some()
with includes()
to check if a string contains any value from an array.
JavaScript provides simple yet effective methods to check for values in arrays and strings. Depending on the use case, you can either check for an exact match in an array using indexOf()
or find a substring match in a string using some()
with includes()
.
By implementing these methods, developers can efficiently search and manipulate string and array data in JavaScript applications.