Javascript Regex match everything after last occurrence of string

后端 未结 1 341
小蘑菇
小蘑菇 2021-01-14 11:44

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         


        
1条回答
  •  执念已碎
    2021-01-14 11:56

    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;
    

    0 讨论(0)
提交回复
热议问题