EndsWith 方法不匹配以问号结尾的字符串
有没有一种简单的方法可以使此函数/方法适用于以问号结尾的字符串?
String.prototype.EndsWith = function(str){return (this.match(str+"$")==str)}
var aa='a cat';
var bb='a cat?';
if( aa.EndsWith('cat') ){
document.write('cat matched'+'<br\/>');
}
if( bb.EndsWith('cat?') ){
document.write('cat? matched');
}
在当前状态下,仅匹配第一个测试(cat)。
Is there a simple way to make this function/method work with strings that end with a question mark?
String.prototype.EndsWith = function(str){return (this.match(str+"$")==str)}
var aa='a cat';
var bb='a cat?';
if( aa.EndsWith('cat') ){
document.write('cat matched'+'<br\/>');
}
if( bb.EndsWith('cat?') ){
document.write('cat? matched');
}
In the current state, only the first test is matched (cat).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我会跳过正则表达式并执行以下操作:
I'd skip the regex and just do this:
如果您要使用基于当前字符串的正则表达式,则必须转义正则表达式中具有特殊含义的所有字符,因此不仅仅是问号,还有您看到的所有其他字符 此处。
我认为使用
.lastIndexOf()< 会更容易/代码>
:
If you're going to use a regular expression that is based on the current string you'll have to escape all of the characters that have special meaning in a regular expression, so not just question marks, but everything else you see here.
I think it would be much easier to use
.lastIndexOf()
:我不会将其作为一种方法 - 只需在需要时编写适当的 reg exp 即可。
I wouldn't make it a method- just write the appropriate reg exp when you need one.
PS:
请注意,函数应以小写字母开头。小提琴:http://jsfiddle.net/USzfa/4/
P.S. :
Please note that a function should start with lowercase.fiddle : http://jsfiddle.net/USzfa/4/