Jquery 检查两个值是否以相同文本开头

标签 jquery string variables

我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/

相关文章:

循环中的 C 变量变化

javascript - 如何获取div的第一个 child 的属性?

javascript - jQuery如何将事件绑定(bind)到被删除并再次添加的元素

jquery - 当最后一行在浏览器中可见时,如何将行追加到表中?

javascript - 在Codeigniter中显示JQgrid中的动态数据

python - 如何使用列表替换字符串的某些部分?

c - 为什么我会出现段错误核心转储?

c++ - 警告 : array 'alphabet' initialized by parenthesized string literal

javascript - 如果我将一个元素存储在 JavaScript 变量中,当我调用该变量时它会再次检查它吗?

javascript - 第一次获得总数没问题,但是当更改折扣或数量时会给出错误的结果