Reputation:
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).
Upvotes: 0
Views: 481
Reputation: 18588
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/
Upvotes: 0
Reputation: 104840
I wouldn't make it a method- just write the appropriate reg exp when you need one.
if(/cat[.'"?!]*$/.test(aa)){
}
Upvotes: 0
Reputation: 150070
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);
}
Upvotes: 0
Reputation: 298532
I'd skip the regex and just do this:
String.prototype.EndsWith = function(str) {
return (this.lastIndexOf(str) == this.length - str.length);
}
Upvotes: 1