JavaScript EndsWith 函数不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18768344/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript endsWith function not working
提问by nudastack
I have a web application. In one of the pages, I go all over the HTML element IDs wether one of them ends with a specified string or not. Every JS functions work on the page but "endsWith" function doesn't work. I really didn't understand the matter. Can anyone help?
我有一个网络应用程序。在其中一个页面中,我遍历了 HTML 元素 ID,无论其中一个是否以指定的字符串结尾。每个 JS 函数都可以在页面上运行,但“endsWith”函数不起作用。我真的不明白这件事。任何人都可以帮忙吗?
var str = "To be, or not to be, that is the question.";
alert(str.endsWith("question."));
The above simple JS code doesn't work at all?
上面简单的JS代码根本就不行?
回答by vikas devde
As said in this post http://rickyrosario.com/blog/javascript-startswith-and-endswith-implementation-for-strings/
正如这篇文章中所说的http://rickyrosario.com/blog/javascript-startswith-and-endswith-implementation-for-strings/
var str = "To be, or not to be, that is the question.";
function strEndsWith(str, suffix) {
return str.match(suffix+"$")==suffix;
}
alert(strEndsWith(str,"question."));
this will return true if it ends with provided suffix.
如果以提供的后缀结尾,则返回 true。
EDIT
编辑
There is a similar question asked before check it here
在这里检查之前有一个类似的问题
the answer says
答案说
var str = "To be, or not to be, that is the question$";
String.prototype.endsWith = function(suffix) {
return this.indexOf(suffix, this.length - suffix.length) !== -1;
};
alert(str.endsWith("$"));
回答by SheetJS
ES5 has no endsWith
function (or, for that matter, startsWith
). You can roll your own, like this version from MDN:
ES5 没有任何endsWith
功能(或者,就此而言,startsWith
)。你可以推出自己的,就像来自MDN 的这个版本:
if (!String.prototype.endsWith) {
Object.defineProperty(String.prototype, 'endsWith', {
enumerable: false,
configurable: false,
writable: false,
value: function (searchString, position) {
position = position || this.length;
position = position - searchString.length;
var lastIndex = this.lastIndexOf(searchString);
return lastIndex !== -1 && lastIndex === position;
}
});
}
回答by J D
I have never seen an endsWith
function in JS. You can rather do an String.length and then check the last words by manually referencing each character you want to check against.
我从未见过endsWith
JS 中的函数。你可以做一个 String.length 然后通过手动引用你想要检查的每个字符来检查最后一个单词。
Even better would be to do a regex to find the last word in the string and then use that (Regular expression to find last word in sentence).
更好的是做一个正则表达式来查找字符串中的最后一个单词,然后使用它(正则表达式查找句子中的最后一个单词)。