我想知道字符串是否以指定的字符/字符串开始或在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');
}

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


当前回答

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

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

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

其他回答

你可以像这样扩展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

首先,你可以使用indexOf:

if(str.indexOf('Hello') == 0) {

...

ref

你可以根据字符串长度来计算“endswith”。

if(str.lastIndexOf('Hello') == str.length - 'Hello'.length) {

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

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

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

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