string - endsWith in JavaScript -


how can check if string ends particular character in javascript?

example: have string

var str = "mystring#"; 

i want know if string ending #. how can check it?

  1. is there endswith() method in javascript?

  2. one solution have take length of string , last character , check it.

is best way or there other way?

update (nov 24th, 2015):

this answer posted in year 2010 (six years back.) please take note of these insightful comments:


original answer:

i know year old question... need , need work cross-browser so... combining everyone's answer , comments , simplifying bit:

string.prototype.endswith = function(suffix) {     return this.indexof(suffix, this.length - suffix.length) !== -1; }; 
  • doesn't create substring
  • uses native indexof function fastest results
  • skip unnecessary comparisons using second parameter of indexof skip ahead
  • works in internet explorer
  • no regex complications

also, if don't stuffing things in native data structure's prototypes, here's standalone version:

function endswith(str, suffix) {     return str.indexof(suffix, str.length - suffix.length) !== -1; } 

edit: noted @hamish in comments, if want err on safe side , check if implementation has been provided, can adds typeof check so:

if (typeof string.prototype.endswith !== 'function') {     string.prototype.endswith = function(suffix) {         return this.indexof(suffix, this.length - suffix.length) !== -1;     }; } 

Comments

Popular posts from this blog

curl - PHP fsockopen help required -

HTTP/1.0 407 Proxy Authentication Required PHP -

c# - Resource not found error -