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

3

5
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

Miasma answered 7/5, 2015 at 18:15 Comment(3)
javascript im assuming?Prolegomenon
Which programming language are you using and what have you tried so far ? Further, this case can be solved with a simple "substring" - why do you want to use regex which is way inferior from performance perspective ?Proa
sorry yes it is javascriptMiasma
K
5

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

longString.endsWith(shortString)
Keane answered 7/5, 2015 at 18:21 Comment(3)
endsWith() seems to be added with an external library.Prolegomenon
Ignore that comment. This has been added to the ECMAScript 6 specification. Not all javascript implementations may support it yet however. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…Prolegomenon
Well, for the time being, you can use a polyfill library such as the ones mentioned in ES6-toolsHass
I
2

You can use the following if you need regex:

var matcher = new RegExp(shortString + "\$", "g");
var found = matcher.test(longString );
Inaccessible answered 7/5, 2015 at 18:21 Comment(1)
The $ should need to be escaped. Also shouldnt need to globally check on a single line.Prolegomenon
P
1

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

Prolegomenon answered 7/5, 2015 at 18:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.