EndsWith 方法不匹配以问号结尾的字符串

发布于 2024-12-21 16:18:51 字数 352 浏览 1 评论 0原文

有没有一种简单的方法可以使此函数/方法适用于以问号结尾的字符串?

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

执妄 2024-12-28 16:18:51

我会跳过正则表达式并执行以下操作:

String.prototype.EndsWith = function(str) {
  return (this.lastIndexOf(str) == this.length - str.length);
}

I'd skip the regex and just do this:

String.prototype.EndsWith = function(str) {
  return (this.lastIndexOf(str) == this.length - str.length);
}
小嗷兮 2024-12-28 16:18:51

如果您要使用基于当前字符串的正则表达式,则必须转义正则表达式中具有特殊含义的所有字符,因此不仅仅是问号,还有您看到的所有其他字符 此处

我认为使用 .lastIndexOf()< 会更容易/代码>

String.prototype.EndsWith = function(str){
   return (this.lastIndexOf(str) === this.length - str.length);
}

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():

String.prototype.EndsWith = function(str){
   return (this.lastIndexOf(str) === this.length - str.length);
}
影子是时光的心 2024-12-28 16:18:51

我不会将其作为一种方法 - 只需在需要时编写适当的 reg exp 即可。

if(/cat[.'"?!]*$/.test(aa)){
}

I wouldn't make it a method- just write the appropriate reg exp when you need one.

if(/cat[.'"?!]*$/.test(aa)){
}
月亮邮递员 2024-12-28 16:18:51

PS: 请注意,函数应以小写字母开头。

String.prototype.endsWith = function(str){
    return (this.lastIndexOf(str) === this.length - str.length)            
  }

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');
}

小提琴:http://jsfiddle.net/USzfa/4/

P.S. : Please note that a function should start with lowercase.

String.prototype.endsWith = function(str){
    return (this.lastIndexOf(str) === this.length - str.length)            
  }

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');
}

fiddle : http://jsfiddle.net/USzfa/4/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文