我jquery如何检查以相同文本开头的两个值,
我的代码是
$a = "Hello john";
$b = "Hello peter";
$a == $b --> 假
像这样如何查找以字符串开头的变量。
最佳答案
方法 1
<强> Click here for the demo
if (!String.prototype.startsWith) {
Object.defineProperty(String.prototype, 'startsWith', {
enumerable: false,
configurable: false,
writable: false,
value: function (searchString, position) {
position = position || 0;
return this.indexOf(searchString, position) === position;
}
});
}
var str = "Pankaj Garg";
alert(str.startsWith("Pankaj")); // true
alert(str.startsWith("Garg")); // false
alert(str.startsWith("Garg", 7)); // true
如果您留意第三个提醒,也可以在留下一些字符后开始比较
<小时/>方法 2
Click here for the Demo
if (typeof String.prototype.startsWith != 'function') {
String.prototype.startsWith = function (str){
return this.indexOf(str) == 0;
};
}
var data = "Hello world";
var input = 'He';
if(data.startsWith(input))
{
alert("ok");
}
else
{
alert("not ok");
}
方法 3
<强> Check here for the Demo
var str = "Hello A";
var str1 = "Hello B";
if(str.match("^Hello") && str1.match("^Hello"))
{
alert('ok');
}
else
{
alert('not ok');
}
关于Jquery 检查两个值是否以相同文本开头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16561359/