JavaScript or jQuery string ends with utility function

What is the easiest way to find out if a string ends with a specific value?

+67
javascript jquery
Jul 07 '09 at 22:27
source share
8 answers

you can use regexps, for example:

str.match(/value$/) 

which will return true if the string has a value at the end ($).

+148
Jul 07 '09 at 22:31
source share

Stolen from prototypes:

 String.prototype.endsWith = function(pattern) { var d = this.length - pattern.length; return d >= 0 && this.lastIndexOf(pattern) === d; }; 'slaughter'.endsWith('laughter'); // -> true 
+36
Jul 07 '09 at 22:30
source share

Regular expressions

 "Hello world".match(/world$/) 
+9
Jul 07 '09 at 22:32
source share

I had no luck with a coincidence, but it worked:

If you have a line, "This is my line." and would like to see if this ends with a period, do the following:

 var myString = "This is my string."; var stringCheck = "."; var foundIt = (myString.lastIndexOf(stringCheck) === myString.length - stringCheck.length) > 0; alert(foundIt); 

You can change the stringCheck variable to any string for verification. It would be best to throw this into your own function as follows:

 function DoesStringEndWith(myString, stringCheck) { var foundIt = (myString.lastIndexOf(stringCheck) === myString.length - stringCheck.length) > 0; return foundIt; } 
+4
Jul 03 2018-12-12T00:
source share

I am simply expanding on what @ luca-matteis posted, but in order to solve the problems mentioned in the comments, the code should be wrapped to make sure that you are not overwriting your own implementation.

 if ( !String.prototype.endsWith ) { String.prototype.endsWith = function(pattern) { var d = this.length - pattern.length; return d >= 0 && this.lastIndexOf(pattern) === d; }; } 

This is the proposed method for the Array.prototype.forEach method, as specified on the mozilla dev network

+1
May 12 '12 at
source share

ES6 supports this directly:

 'this is dog'.endsWith('dog') //true 
+1
Sep 07 '16 at 15:07
source share

You can do 'hello world'.slice(-5)==='world' . It works in all browsers. Much faster than regex.

+1
Nov 17 '16 at 16:45
source share

You can always prototype the String class, this will work:

String.prototype.endsWith = function (str) {return (this.match (str + "$") == str)}

You can find other related extensions for the String class at http://www.tek-tips.com/faqs.cfm?fid=6620

0
Oct. 15 2018-10-15
source share



All Articles