@chakrit 's accepted answer is a solid way to do it yourself. If, however, you'正在寻找一个打包的解决方案,我建议看看underscore.string,正如@mlunoe指出的那样 . 使用underscore.string,代码将是:
function endsWithHash(str) {
return _.str.endsWith(str, '#');
}
1728
对于这么小的问题,这么多东西,只需使用这个正则表达式
var str = "mystring#";
var regex = /^.*#$/
if (regex.test(str)){
//if it has a trailing '#'
}
function strEndsWith(str,suffix) {
if (str[str.length - 1] == suffix) return true;
return false;
}
7
if(typeof String.prototype.endsWith !== "function") {
/**
* String.prototype.endsWith
* Check if given string locate at the end of current string
* @param {string} substring substring to locate in the current string.
* @param {number=} position end the endsWith check at that position
* @return {boolean}
*
* @edition ECMA-262 6th Edition, 15.5.4.23
*/
String.prototype.endsWith = function(substring, position) {
substring = String(substring);
var subLen = substring.length | 0;
if( !subLen )return true;//Empty string
var strLen = this.length;
if( position === void 0 )position = strLen;
else position = position | 0;
if( position < 1 )return false;
var fromIndex = (strLen < position ? strLen : position) - subLen;
return (fromIndex >= 0 || subLen === -fromIndex)
&& (
position === 0
// if position not at the and of the string, we can optimise search substring
// by checking first symbol of substring exists in search position in current string
|| this.charCodeAt(fromIndex) === substring.charCodeAt(0)//fast false
)
&& this.indexOf(substring, fromIndex) === fromIndex
;
};
}
position :在此字符串中搜索,就好像这个字符串只有这么长;默认为此字符串's actual length, clamped within the range established by this string'的长度 .
说明
此方法允许您确定字符串是否以另一个字符串结尾 .
例子
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
var myStr = “ Earth is a beautiful planet ”;
var myStr2 = myStr.trim();
//==“Earth is a beautiful planet”;
if (myStr2.startsWith(“Earth”)) // returns TRUE
if (myStr2.endsWith(“planet”)) // returns TRUE
if (myStr.startsWith(“Earth”))
// returns FALSE due to the leading spaces…
if (myStr.endsWith(“planet”))
// returns FALSE due to trailing spaces…
传统的方式
function strStartsWith(str, prefix) {
return str.indexOf(prefix) === 0;
}
function strEndsWith(str, suffix) {
return str.match(suffix+"$")==suffix;
}
2
function strEndsWith(str,suffix) {
var reguex= new RegExp(suffix+'$');
if (str.match(reguex)!=null)
return true;
return false;
}
0
String.prototype.endWith = function (a) {
var isExp = a.constructor.name === "RegExp",
val = this;
if (isExp === false) {
a = escape(a);
val = escape(val);
} else
a = a.toString().replace(/(^\/)|(\/$)/g, "");
return eval("/" + a + "$/.test(val)");
}
// example
var str = "Hello";
alert(str.endWith("lo"));
alert(str.endWith(/l(o|a)/));
String.prototype.endsWith = function (s) {
return this.length >= s.length && this.substr(this.length - s.length) == s;
}
如果没有匹配,使用 lastIndexOf 只会创建不必要的CPU循环 .
1
7岁的帖子,但我无法理解前几个帖子,因为它们很复杂 . 所以,我写了自己的解决方案:
function strEndsWith(str, endwith)
{
var lastIndex = url.lastIndexOf(endsWith);
var result = false;
if (lastIndex > 0 && (lastIndex + "registerc".length) == url.length)
{
result = true;
}
return result;
}
30 回答
经过所有这些长长的答案,我发现这段代码简单易懂!
这是endsWith的实现:
String.prototype.endsWith = function(str){return this.length> = str.length && this.substr(this.length - str.length)== str; }
@chakrit 's accepted answer is a solid way to do it yourself. If, however, you'正在寻找一个打包的解决方案,我建议看看underscore.string,正如@mlunoe指出的那样 . 使用underscore.string,代码将是:
对于这么小的问题,这么多东西,只需使用这个正则表达式
将适用于所有浏览器,不需要猴子修补
String
,并且不需要扫描整个字符串,因为lastIndexOf
没有匹配时 .如果要匹配可能包含正则表达式特殊字符的常量字符串,例如
'$'
,则可以使用以下命令:然后你可以像这样使用它
这个版本避免了创建子字符串,并且不使用正则表达式(这里的一些正则表达式答案将起作用;其他正在破坏):
如果性能对您很重要,那么测试
lastIndexOf
实际上是否比创建子字符串更快是值得的 . (它很可能取决于你真正关心的JS引擎:(要检查单个字符,找到长度然后使用
charAt
可能是最好的方法 .不幸的是没有 .
if( "mystring#".substr(-1) === "#" ) {}
如果你不想使用lasIndexOf或substr那么为什么不只看它的自然状态的字符串(即一个数组)
或作为独立功能
Benefits:
此版本不仅仅是重复使用indexOf .
长串上的最佳表现 . 这是速度测试http://jsperf.com/starts-ends-with/4
与ecmascript规范完全兼容 . 它通过tests
UPDATE (Nov 24th, 2015):
这个答案最初发布于2010年(六年前) . 所以请注意这些富有洞察力的评论:
Shauna - Google员工更新 - 看起来ECMA6添加了此功能 . MDN文章还显示了polyfill . https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith
T.J. Crowder - 在现代浏览器上创建子串并不昂贵;这个答案发布时,可能是在2010年 . 目前,简单的
this.substr(-suffix.length) === suffix
方法在Chrome上最快,在IE11上与indexOf相同,在Firefox上只有4%的速度(fergetaboutit领域):jsperf.com/endswith-stackoverflow/14当结果为假时,整个过程更快:jsperf.com/endswith-stackoverflow-when-false Of course, with ES6 adding endsWith, the point is moot. :-)ORIGINAL ANSWER:
我知道这是一年前的问题...但我也需要这个,我需要它跨浏览器工作所以... combining everyone's answer and comments 并简化它:
不创建子字符串
使用原生
indexOf
函数以获得最快结果使用
indexOf
的第二个参数跳过不必要的比较以跳过在Internet Explorer中工作
没有正则表达式的并发症
此外,如果您不喜欢在本机数据结构的原型中填充东西,这里是一个独立版本:
EDIT: 正如@hamish在评论中指出的那样,如果您想在安全方面犯错并检查是否已提供实施,您可以添加
typeof
检查,如下所示:来自developer.mozilla.org String.prototype.endsWith()
摘要
endsWith()
方法确定字符串是否以另一个字符串的字符结尾,并根据需要返回true或false .语法
参数
searchString :此字符串末尾要搜索的字符 .
position :在此字符串中搜索,就好像这个字符串只有这么长;默认为此字符串's actual length, clamped within the range established by this string'的长度 .
说明
此方法允许您确定字符串是否以另一个字符串结尾 .
例子
规格
ECMAScript Language Specification 6th Edition (ECMA-262)
浏览器兼容性
所有这些都是非常有用的例子 . 添加
String.prototype.endsWith = function(str)
将帮助我们简单地调用方法来检查我们的字符串是否以它结束,regexp也会这样做 .我找到了比我更好的解决方案 . 感谢大家 .
这个问题花了很多年 . 让我为想要使用最多投票的chakrit答案的用户添加一个重要的更新 .
'endsWith'函数已作为ECMAScript 6(实验技术)的一部分添加到JavaScript中
请参考此处:https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith
因此,强烈建议添加检查是否存在本机实现,如答案中所述 .
将来测试未来证明和/或防止覆盖现有原型的方法检查它是否已经添加到String原型中 . 这是我对非正则表达式高评级版本的看法 .
使用正则表达式的另一个快速替代方案对我来说就像一个魅力:
这 Build 在@ charkit接受的答案之上,允许一个字符串数组或字符串作为参数传入 .
这需要下划线 - 但可以调整以删除下划线依赖项 .
对于coffeescript
如果你正在使用lodash:
如果不使用lodash,你可以借用source .
我不了解你,但是:
为什么正则表达式为什么搞乱原型? SUBSTR?来吧...
没有看到
slice
方法的apporach . 所以我就把它留在这里:我刚刚了解了这个字符串库:
http://stringjs.com/
包括js文件,然后使用
S
变量,如下所示:它也可以通过安装在NodeJS中使用:
然后要求它作为
S
变量:该网页还包含指向备用字符串库的链接,如果这个图书馆没有您喜欢的话 .
我希望这有帮助
传统的方式
不要使用正则表达式 . 即使在快速语言中它们也很慢 . 只需编写一个检查字符串结尾的函数 . 这个库有很好的例子:groundjs/util.js . 小心向String.prototype添加一个函数 . 这段代码有很好的例子说明如何:groundjs/prototype.js一般来说,这是一个很好的语言级库:groundjs你也可以看看lodash
在原始字符串长度比搜索字符串长度小1并且找不到搜索字符串的情况下不起作用:
lastIndexOf返回-1,然后添加搜索字符串长度,并保留原始字符串的长度 .
可能的解决办法是
来吧,这是正确的
endsWith
实现:如果没有匹配,使用
lastIndexOf
只会创建不必要的CPU循环 .7岁的帖子,但我无法理解前几个帖子,因为它们很复杂 . 所以,我写了自己的解决方案: