ArticleZip > How To Check If A String Contains Text From An Array Of Substrings In Javascript

How To Check If A String Contains Text From An Array Of Substrings In Javascript

In JavaScript, checking if a string contains any text from an array of substrings can be a useful task when working on projects that involve validating user input or searching for specific keywords within a larger text. In this article, we'll cover a simple and efficient way to achieve this using JavaScript.

To start, you'll first need to have an array of substrings that you want to check against your string. This array can contain any number of substrings that you want to search for in the main string.

Next, we'll write a function that takes in the main string and the array of substrings as parameters. Within this function, we'll iterate over the array and for each substring, we'll use the JavaScript `includes()` method to check if the main string contains that specific substring. The `includes()` method returns true if the string contains the specified value, otherwise it returns false.

Here's a sample implementation of the function:

Javascript

function checkIfStringContainsSubstrings(mainString, substringsArray) {
    for (let i = 0; i < substringsArray.length; i++) {
        if (mainString.includes(substringsArray[i])) {
            return true;
        }
    }
    return false;
}

In the code snippet above, the `checkIfStringContainsSubstrings()` function takes the `mainString` and `substringsArray` as input parameters. It then iterates over each substring in the array and uses the `includes()` method to check if the main string contains that particular substring. If a match is found, the function returns true indicating that the main string contains one of the substrings. If no match is found after iterating through all the substrings, the function returns false.

You can now call this function in your code and pass the main string and the array of substrings to check if the main string contains any of the substrings. Here's an example of how you can use this function:

Javascript

let mainString = "Hello, this is a sample string.";
let substringsArray = ["sample", "text", "example"];

if (checkIfStringContainsSubstrings(mainString, substringsArray)) {
    console.log("The main string contains one of the substrings.");
} else {
    console.log("The main string does not contain any of the substrings.");
}

In the above example, we have a `mainString` that contains the text "Hello, this is a sample string." and an `substringsArray` containing "sample", "text", and "example". The `checkIfStringContainsSubstrings()` function is called with these parameters, and based on the result, a message is logged to the console.

By using this straightforward approach, you can easily check if a string contains any text from an array of substrings in JavaScript. This method is efficient and can be customized based on your specific requirements.