I am trying to match everything after (but not including!) the last occurrence of a string in JavaScript.
The search, for example, is:
[quote=\"use
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;