下面的JS代码,为String对象定义了一个contains方法用于判断字符串是否包含子字符串,非常有用。
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; } } // http://www.75271.com if (!String.prototype.contains) { String.prototype.contains = function (arg) { return !!~this.indexOf(arg); }; }
下面是一个详细的使用范例,可以在浏览器内执行
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; } } // http://www.75271.com/codes/ 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>