如何知道字符串在jQuery中以特定字符串开头/结尾?

Nav*_*eed 200 javascript string jquery

我想知道一个字符串是以指定的字符/字符串开头还是以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');
}
Run Code Online (Sandbox Code Playgroud)

如果没有任何功能那么任何替代方案?

Luk*_*ský 377

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

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

if (str.match("World$")) {
   // do this if ends in world
}
Run Code Online (Sandbox Code Playgroud)

  • 传递一个正则表达式对象而不是一个正则表达式字符串似乎解决了问题@nokturnal提到:`str.match(/ ^ Hello /)`但形式`/regex/.test(str)`对于这种特殊情况更好,根据http://stackoverflow.com/questions/10940137/regex-test-vs-string-match-to-know-if-a-string-matches-a-regular-expression (22认同)
  • 请注意,您正在检查的字符串不包含任何正则表达式保留字符. (2认同)

sje*_*397 92

对于startswith,您可以使用indexOf:

if(str.indexOf('Hello') == 0) {
Run Code Online (Sandbox Code Playgroud)

...

REF

你可以根据字符串长度做数学来确定'endswith'.

if(str.lastIndexOf('Hello') == str.length - 'Hello'.length) {
Run Code Online (Sandbox Code Playgroud)

  • 你可能想使用`lastIndexOf()`作为endswith;) (10认同)
  • 比使用正则表达式这样一个简单的用例更安全的答案.应该接受答案. (3认同)

小智 23

不需要jQuery来做到这一点.你可以编写一个jQuery包装器但它没用,所以你应该更好地使用它

var str = "Hello World";

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

window.alert("Ends with Hello ? " + /Hello$/i.test(str));
Run Code Online (Sandbox Code Playgroud)

因为不推荐使用match()方法.

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

  • 你能提供一个关于match()被弃用的文档的链接吗?快速谷歌搜索不会返回任何内容. (2认同)

Sal*_*ali 15

你真的不需要jQuery来完成这些任务.在ES6规范中,他们已经开箱即用方法startsWithendsWith.

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
Run Code Online (Sandbox Code Playgroud)

目前可在FF和Chrome中使用.对于旧版浏览器,您可以使用其polyfill或substr


Mr.*_*kin 9

您总是可以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;
    };
}
Run Code Online (Sandbox Code Playgroud)

并像这样使用它:

var str = 'Hello World';

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

if( str.endsWith('World') ) {
   // your string ends with 'World'
}
Run Code Online (Sandbox Code Playgroud)