Find a String within another String using JavaScript

arp14 JavaScript Tags: 0

This code snippet is to search a string within another string.

var haystack = "A quick brown fox jumped over the lazy dog."
var needle = "dog";
var position = haystack.indexOf(needle);

// for case sensitive search comment out the line below
haystack = haystack.toLowerCase();

// alert(position); // get position of needle

if (position == -1) {
    // not found
    alert ("not found")
    // do stuffs
} else {
    // found
    alert ("found")
    // do stuffs
}

The same code as function:

// returns 1 if found, else 0
function searchStr(haystack, needle){
    // for case sensitive search comment out the line below
    haystack = haystack.toLowerCase();
    if (haystack.indexOf(needle) == -1) return 0; // not found
    else return 1; // found
}

// usage
var haystack = "A quick brown fox jumped over the lazy dog."
var needle = "dog";

alert(searchStr(haystack, needle));

Leave a Reply

Note: Your email address will not be published. Required fields are marked *