jQuery Check if String Contains Specific Word

While working with jQuery and JavaScript, one of the most common tasks developers face is checking whether a string contains a specific word or substring.

Whether you’re validating user input, filtering content, or implementing search functionality, knowing how to efficiently check string contents is essential for modern web development.

In this article, I will explain to you the methods to check if string contains specific word with real-world examples.

String Validation in jQuery

String validation is crucial for creating robust web applications. From form validation to content filtering, the ability to check if a string contains specific words helps prevent security vulnerabilities, improve user experience, and maintain data integrity.

Method 1: Use JavaScript’s includes() Method

The includes() method is the easiest and modern approach for checking if a string contains a specific word.

Basic Syntax and Example

$(document).ready(function() {
    var mainString = "Welcome to our jQuery tutorial website";
    var searchWord = "jQuery";

    if (mainString.includes(searchWord)) {
        console.log("String contains the word: " + searchWord);
        $("#result").text("Found: " + searchWord);
    } else {
        console.log("String does not contain the word");
        $("#result").text("Word not found");
    }
});

I executed the above example code and added the screenshot below.

Check if String Contains Specific Word in jQuery

Case-Sensitive vs Case-Insensitive Search

The includes() method is case-sensitive by default. For case-insensitive searches:

$(document).ready(function() {
    var mainString = "JavaScript and jquery are powerful";
    var searchWord = "jQuery";

    // Case-insensitive check
    if (mainString.toLowerCase().includes(searchWord.toLowerCase())) {
        $("#result").text("Word found (case-insensitive)");
    }
});

Method 2: Use indexOf() Method

The indexOf() method returns the position of the first occurrence of a substring, or -1 if not found.

$(document).ready(function() {
    var textContent = "Learning jQuery makes web development easier";
    var targetWord = "jQuery";

    if (textContent.indexOf(targetWord) !== -1) {
        var position = textContent.indexOf(targetWord);
        $("#output").html("Word found at position: " + position);
    } else {
        $("#output").html("Word not found");
    }
});

I executed the above example code and added the screenshot below.

jQuery Check if String Contains Specific Word

Advanced indexOf() Example with Multiple Checks

Checks the provided words array against the main string (case-insensitive) and returns a list of any matches.

function checkMultipleWords(mainString, wordsArray) {
    var foundWords = [];

    $.each(wordsArray, function(index, word) {
        if (mainString.toLowerCase().indexOf(word.toLowerCase()) !== -1) {
            foundWords.push(word);
        }
    });

    return foundWords;
}

// Usage example
$(document).ready(function() {
    var content = "jQuery and JavaScript are essential for modern web development";
    var searchWords = ["jQuery", "CSS", "JavaScript", "HTML"];
    var results = checkMultipleWords(content, searchWords);

    $("#results").html("Found words: " + results.join(", "));
});

Method 3: Use jQuery’s :contains() Selector

jQuery provides a :contains() selector specifically for finding elements containing specific text.

$(document).ready(function() {
    // Highlight paragraphs containing specific words
    $("p:contains('jQuery')").css({
        "background-color": "yellow",
        "font-weight": "bold"
    });

    // Check if any elements contain the word
    if ($("div:contains('tutorial')").length > 0) {
        console.log("Found elements containing 'tutorial'");
    }
});

I executed the above example code and added the screenshot below.

Check String Contains Specific Word or not in jQuery

Method 4: Regular Expressions for Advanced Pattern Matching

For more complex string matching requirements, regular expressions offer powerful capabilities:

$(document).ready(function() {
    function containsWordRegex(str, word) {
        var regex = new RegExp("\\b" + word + "\\b", "i");
        return regex.test(str);
    }

    var sentence = "jQuery is a powerful JavaScript library";
    var searchTerm = "jQuery";

    if (containsWordRegex(sentence, searchTerm)) {
        $("#regex-result").text("Exact word match found!");
    }
});

Real-World Implementation: Form Validation

Here’s a practical example combining multiple methods for form validation:

$(document).ready(function() {
    $("#user-form").on("submit", function(e) {
        var userInput = $("#message").val();
        var forbiddenWords = ["spam", "advertisement", "promotion"];
        var containsForbidden = false;

        // Check for forbidden words
        $.each(forbiddenWords, function(index, word) {
            if (userInput.toLowerCase().includes(word.toLowerCase())) {
                containsForbidden = true;
                return false; // Break the loop
            }
        });

        if (containsForbidden) {
            e.preventDefault();
            $("#error-message").text("Message contains forbidden words");
            $("#error-message").show();
        } else {
            $("#error-message").hide();
            // Allow form submission
        }
    });
});

Performance Considerations and Best Practices

1. Choose the Right Method

  • Use includes() for simple substring checks
  • Use indexOf() when you need the position information
  • Use regular expressions for complex pattern matching
  • Use jQuery selectors for DOM element filtering

2. Optimize for Performance

Caches jQuery selections to avoid repeated DOM queries, then checks and highlights matching <p> elements.

// Cache jQuery objects
var $elements = $("p");
var searchTerm = "jQuery";

// More efficient than repeated selections
$elements.each(function() {
    if ($(this).text().includes(searchTerm)) {
        $(this).addClass("highlighted");
    }
});

3. Handle Edge Cases

Safely checks for null/undefined, coerces inputs to strings, and performs a case-insensitive containment test.

function safeStringContains(str, searchTerm) {
    // Handle null/undefined values
    if (!str || !searchTerm) {
        return false;
    }

    // Convert to string if needed
    return String(str).toLowerCase().includes(String(searchTerm).toLowerCase());
}

Browser Compatibility and Modern Alternatives

The includes() method is supported in all modern browsers (IE 9+). For older browser support, consider using polyfills or falling back to indexOf() method.

// Polyfill for older browsers
if (!String.prototype.includes) {
    String.prototype.includes = function(search, start) {
        return this.indexOf(search, start) !== -1;
    };
}

Conclusion

String containment checks in jQuery are essential for creating dynamic, interactive web applications. Whether using the modern includes() method, the reliable indexOf() approach, or jQuery’s specialized selectors, each technique has its place in a developer’s toolkit. By combining these methods with proper validation and performance optimization, you can create robust applications that handle string operations efficiently and securely.

Remember to always consider case sensitivity, handle edge cases, and choose the most appropriate method based on your specific requirements. With these techniques in your arsenal, you’ll be well-equipped to handle any string validation challenge in your jQuery projects.

You may also read:

Leave a Comment

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.