ManreeRist
ManreeRist

Reputation: 504

Javascript Regex match everything after last occurrence of string

I am trying to match everything after (but not including!) the last occurrence of a string in JavaScript.

The search, for example, is:

[quote="user1"]this is the first quote[/quote]\n[quote="user2"]this is the 2nd quote and some url https://www.google.com/[/quote]\nThis is all the text I\'m wirting about myself.\n\nLook at me ma. Javascript.

Edit: I'm looking to match everything after the last quote block. So I was trying to match everything after the last occurrence of "quote]" ? Idk if this is the best solution but its what i've been trying.

I'll be honest, i suck at this Regex stuff.. here is what i've been trying with the results..

regex = /(quote\].+)(.*)/ig; // Returns null 
regex = /.+((quote\]).+)$/ig // Returns null  
regex = /( .* (quote\]) .*)$/ig  // Returns null   

I have made a JSfiddle for anyone to have a play with here:

https://jsfiddle.net/au4bpk0e/

Upvotes: 4

Views: 2958

Answers (1)

Josh Crozier
Josh Crozier

Reputation: 241248

One option would be to match everything up until the last [/quote], and then get anything following it. (example)

/.*\[\/quote\](.*)$/i

This works since .* is inherently greedy, and it will match every up until the last \[\/quote\].

Based on the string you provided, this would be the first capturing group match:

\nThis is all the text I\'m wirting about myself.\n\nLook at me ma. Javascript.

But since your string contains new lines, and . doesn't match newlines, you could use [\s\S] in place of . in order to match anything.

Updated Example

/[\s\S]*\[\/quote\]([\s\S]*)$/i

You could also avoid regex and use the .lastIndexOf() method along with .slice():

Updated Example

var match = '[\/quote]';
var textAfterLastQuote = str.slice(str.lastIndexOf(match) + match.length);
document.getElementById('res').innerHTML = "Results: " + textAfterLastQuote;

Alternatively, you could also use .split() and then get the last value in the array:

Updated Example

var textAfterLastQuote = str.split('[\/quote]').pop();
document.getElementById('res').innerHTML = "Results: " + textAfterLastQuote;

Upvotes: 8

Related Questions