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?
is there
endswith()
method in javascript?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:
shauna - update googlers - looks ecma6 adds function. mdn article shows polyfill. https://developer.mozilla.org/en-us/docs/web/javascript/reference/global_objects/string/endswith
t.j. crowder - creating substrings isn't expensive on modern browsers; may have been in 2010 when answer posted. these days, simple
this.substr(-suffix.length) === suffix
approach fastest on chrome, same on ie11 indexof, , 4% slower (fergetaboutit territory) on firefox: jsperf.com/endswith-stackoverflow/14 , faster across board when result false: jsperf.com/endswith-stackoverflow-when-false of course, es6 adding endswith, point moot. :-)
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
Post a Comment