0

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).

Matt Chan
  • 618
  • 14
  • 25

4 Answers4

1

I'd skip the regex and just do this:

String.prototype.EndsWith = function(str) {
  return (this.lastIndexOf(str) == this.length - str.length);
}
Blender
  • 257,973
  • 46
  • 399
  • 459
  • +1 - I guess that's probably what OP is going for - I thought he wanted to test if a string ends in a question mark, given his first sentence, but this probably makes more sense. – Adam Rackis Dec 17 '11 at 05:31
  • I actually have an array with different strings (some ending with special characters like the question mark, but others just plain letters). Blender's answer works for all. Thank you all for the help! –  Dec 17 '11 at 05:38
  • No problem. I might be using it myself ;) – Blender Dec 17 '11 at 05:39
0

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/

dku.rajkumar
  • 17,470
  • 7
  • 39
  • 57
0

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);
}
nnnnnn
  • 138,378
  • 23
  • 180
  • 229
  • I knew I had to escape the string, but I wasn't sure how. After using the non-regex answer that you and other users gave me, I found this: http://stackoverflow.com/questions/3446170/escape-string-for-use-in-javascript-regex It may be useful for people who can't rely on the index. –  Dec 17 '11 at 08:49
  • Cool. Yes, something like that other answer is what I was alluding to in my first paragraph. Seemed like it would be too easy to accidentally leave out a couple of the special characters, whereas the `.lastIndexOf()` version is pretty bulletproof. – nnnnnn Dec 17 '11 at 11:17
0

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

if(/cat[.'"?!]*$/.test(aa)){
}
kennebec
  • 94,076
  • 30
  • 99
  • 125