Checking if a string contains a certain substring

javascript if string contains

// String.contains
String.prototype.contains = function (s) {
    return~this.indexOf(s)
}

// Print
var print = function (val) {
    document.body.innerHTML = document.body.innerHTML + "<br />" + val
}

// EXAMPLE
if ("foo".contains()) print("foo contains undefined")
if ("foo".contains("o")) print("foo contains 'o'")
if ("foo".contains("asdo")) print("foo contains 'asdo'")

if (!"foo".contains()) print("foo does not contain undefined")
if (!"foo".contains("o")) print("foo does not contain 'o'")
if (!"foo".contains("asdo")) print("foo does not contain 'asdo'")

print("foo".contains("bar"))
print("foo".contains("oo"))
print("foo".contains("oop"))
print("foo".contains(""))
print("foo".contains())
DEMO
Checking if a string contains a certain substring Checking if a string contains a certain substring Reviewed by Bhaumik Patel on 7:05 PM Rating: 5