Thursday, July 3, 2014

Check if String contains another substring in JavaScript

Enter two strings and check if Strign 1 contains String 2.<br> <br>
String 1: <input id="foo" type="text" value="a quick brown fox jumps over">     <br>
String 2: <input id="bar" type="text" value="fox jumps">    <br><br>
<button onclick="checkstring()">Click to check if String 1 contains String 2</button>
<script>
if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function(obj, start) {
         for (var i = (start || 0), j = this.length; i < j; i++) {
             if (this[i] === obj) { return i; }
         }
         return -1;
    }
}

if (!String.prototype.contains) {
    String.prototype.contains = function (arg) {
        return !!~this.indexOf(arg);
    };
}

function checkstring() {
    var foo = document.getElementById("foo").value;
    var bar = document.getElementById("bar").value;

    alert(foo.contains(bar));
}
</script>

No comments:

Post a Comment