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

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


当前回答

首先,你可以使用indexOf:

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

...

ref

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

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

其他回答

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

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

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

不需要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)。

首先,你可以使用indexOf:

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

...

ref

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

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