Jordash
Jordash

Reputation: 3093

Grab data in a string starting from the end of string to the first occurence

I know how to regex match from the start of a string, but am not sure how to do it from the end of string, I need to do this to detect the most recent thing a person typed in, here is an example string:

var string = 'User id[20] EQUALS '20' AND Person Info id[30] EQUALS'

I would want to use Regex to find the most recent id the user typed in, in this case it would be 30

var mostRecentID = string.replace(GRABMOSTRECENT [id] string)

Is this possible?

Upvotes: 1

Views: 36

Answers (1)

anubhava
anubhava

Reputation: 785156

You can use a .replace with a greedy .* match before to make sure we match only last occurrence of id[number]:

var mostRecentID = string.replace(/.*\bid\[(\d+)\].*/, '$1');
//=> 30

RegEx Demo

Upvotes: 3

Related Questions