javascript tutorial - [Solved-5 Solutions] substring - javascript - java script - javascript array



Problem:

How to check if string contains substring?

Solution 1:

$(document).ready(function() {
    $('select[id="Engraving"]').change(function() {
        var str = $('select[id="Engraving"] option:selected').text();
        if (str == "Yes (+ $6.95)") {
            $('.engraving').show();
        } else {
            $('.engraving').hide();
        }
    });
});

click below button to copy the code. By JavaScript tutorial team

Solution 2:

if (str.indexOf("Yes") >= 0)

click below button to copy the code. By JavaScript tutorial team

Solution 3:

could use search or match for this.

str.search( 'Yes' )
click below button to copy the code. By JavaScript tutorial team

will return the position of the match, or -1 if it isn't found.

Solution 4:

var testStr = "This is a test";

if(testStr.contains("test")){
    alert("String Found");
}

click below button to copy the code. By JavaScript tutorial team

Solution 5:

var str = 'It was a good date';
console.log(str.includes('good')); // shows true
console.log(str.includes('Good')); // shows false
click below button to copy the code. By JavaScript tutorial team

To check for a substring, the following approach can be taken

if (mainString.toLowerCase().includes(substringToCheck.toLowerCase())) {
    // mainString contains substringToCheck
}
click below button to copy the code. By JavaScript tutorial team

Related Searches to javascript tutorial - substring