我想知道字符串是否以指定的字符/字符串开始或在jQuery中以它结束。

例如:

var str = 'Hello World';

if( str starts with 'Hello' ) {
   alert('true');
} else {
   alert('false');
}

if( str ends with 'World' ) {
   alert('true');
} else {
   alert('false');
}

如果没有任何功能,那么还有其他选择吗?


当前回答

不需要jQuery来做这些。你可以编写一个jQuery包装器,但它将是无用的,所以你应该更好地使用

var str = "Hello World";

window.alert("Starts with Hello ? " + /^Hello/i.test(str));        

window.alert("Ends with Hello ? " + /Hello$/i.test(str));

因为match()方法已弃用。

注:RegExp中的"i"标志是可选的,代表不区分大小写(因此对于"hello", "hello"等,它也将返回true)。

其他回答

ES6现在支持startsWith()和endsWith()方法来检查字符串的开头和结尾。如果你想支持es6之前的引擎,你可能会考虑在String原型中添加一个建议的方法。

if (typeof String.prototype.startsWith != 'function') {
  String.prototype.startsWith = function (str) {
    return this.match(new RegExp("^" + str));
  };
}

if (typeof String.prototype.endsWith != 'function') {
  String.prototype.endsWith = function (str) {
    return this.match(new RegExp(str + "$"));
  };
}

var str = "foobar is not barfoo";
console.log(str.startsWith("foob"); // true
console.log(str.endsWith("rfoo");   // true

你可以像这样扩展String原型:

//  Checks that string starts with the specific string
if (typeof String.prototype.startsWith != 'function') {
    String.prototype.startsWith = function (str) {
        return this.slice(0, str.length) == str;
    };
}

//  Checks that string ends with the specific string...
if (typeof String.prototype.endsWith != 'function') {
    String.prototype.endsWith = function (str) {
        return this.slice(-str.length) == str;
    };
}

像这样使用它:

var str = 'Hello World';

if( str.startsWith('Hello') ) {
   // your string starts with 'Hello'
}

if( str.endsWith('World') ) {
   // your string ends with 'World'
}

对于这样的任务,实际上并不需要jQuery。在ES6规范中,他们已经有了开箱即用的方法startwith和endsWith。

var str = "To be, or not to be, that is the question.";
alert(str.startsWith("To be"));         // true
alert(str.startsWith("not to be"));     // false
alert(str.startsWith("not to be", 10)); // true

var str = "To be, or not to be, that is the question.";
alert( str.endsWith("question.") );  // true
alert( str.endsWith("to be") );      // false
alert( str.endsWith("to be", 19) );  // true

目前在FF和Chrome可用。对于旧的浏览器,您可以使用它们的polyfills或substr

不需要jQuery来做这些。你可以编写一个jQuery包装器,但它将是无用的,所以你应该更好地使用

var str = "Hello World";

window.alert("Starts with Hello ? " + /^Hello/i.test(str));        

window.alert("Ends with Hello ? " + /Hello$/i.test(str));

因为match()方法已弃用。

注:RegExp中的"i"标志是可选的,代表不区分大小写(因此对于"hello", "hello"等,它也将返回true)。

一种选择是使用正则表达式:

if (str.match("^Hello")) {
   // do this if begins with Hello
}

if (str.match("World$")) {
   // do this if ends in world
}