How to check if a string is the last "part" of another string?

var longString = "this string is long but why" var shortString = "but why" 

How can I check if shortString is not only contained in longString, but actually the last part of the string.

I used indexOf == 0 to check the beginning of a line, but not sure how to get its end

+5
source share
3 answers

You do not need regex if this is javascript, which you can just do:

 longString.endsWith(shortString) 
+5
source

You can use the following if you need a regular expression:

 var matcher = new RegExp(shortString + "\$", "g"); var found = matcher.test(longString ); 
+2
source

You can build regex from shortString and test with match :

 var longString = "this string is long but why"; var shortString = "but why"; // build regex and escape the `$` (end of line) metacharacter var regex = new RegExp(shortString + "\$"); var answer = regex.test(longString); // true console.log(answer); 

Hope this helps

+1
source

All Articles