如何知道一个string开始/结束jQuery中的特定string?

我想知道一个string是以指定的字符/string开头还是以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'); } 

如果没有任何function,那么可以select吗?

一种select是使用正则expression式:

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

对于startswith,你可以使用indexOf:

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

REF

你可以根据string长度来确定'endswith'。

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

没有必要的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()方法已被弃用。

PS:RegExp中的“i”标志是可选的,代表不区分大小写(所以它也会为“hello”,“hEllo”等返回true)。

你并不需要jQuery来完成这些任务。 在ES6规范中,他们已经有了开箱即用的方法startsWith和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

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

es6现在支持startsWith()endsWith()方法来检查string s的开始和结束。 如果你想支持es6以前的引擎,你可能需要考虑在String原型中添加一个build议的方法。

 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 + "$")); }; }