Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I test if a string the last “part” of another string?

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

How can i test if shortString is the not only contained in longString but it is actually the last part of the string.

I used indexOf == 0 to test for the start of the string but not sure how to get the end of it

like image 435
ernerock Avatar asked May 07 '15 18:05

ernerock


Video Answer


3 Answers

You don't need regex, if it is javascript you can just do:

longString.endsWith(shortString)
like image 107
Francesco Di Paolo Avatar answered Oct 11 '22 19:10

Francesco Di Paolo


You can use the following if you need regex:

var matcher = new RegExp(shortString + "\$", "g");
var found = matcher.test(longString );
like image 2
karthik manchala Avatar answered Oct 11 '22 18:10

karthik manchala


You can build a 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

like image 1
ptierno Avatar answered Oct 11 '22 20:10

ptierno