JavaScript RegExp: Can I get the last matched index or search backwards/RightToLeft?

前端 未结 2 1563
迷失自我
迷失自我 2020-12-31 06:45

Suppose I have a string

foo bar baz foo bar baz foo bar baz foo bar baz 

I want to find for the last occurance of bar, how can I effective

相关标签:
2条回答
  • 2020-12-31 07:05
    bar(?!.*bar)
    

    will find the last bar in a string:

    bar   # Match bar
    (?!   # but only if it's not followed by...
     .*   # zero or more characters
     bar  # literal bar
    )     # end of lookahead
    

    If your string may contain newline characters, use

    bar(?![\s\S]*bar)
    

    instead. [\s\S] matches any character, including newlines.

    For example:

    match = subject.match(/bar(?![\s\S]*bar)/);
    if (match != null) {
        // matched text: match[0]
        // match start: match.index
    }
    

    You might also want to surround your search words (if they are indeed words composed of alphanumeric characters) with \b anchors to avoid partial matches.

    \bbar\b(?![\s\S]*\bbar\b)
    

    matches the solitary bar instead of the bar within foobar:

    Don't match bar, do match bar, but not foobar!
      no match---^     match---^    no match---^
    
    0 讨论(0)
  • 2020-12-31 07:16

    Use the built-in function lastIndexOf:

    "foo bar baz foo bar baz foo bar baz foo bar baz".lastIndexOf("bar");
    

    If you want to find the last "word" "bar":

    (" "+"foo bar baz foo bar baz foo bar baz foo bar baz"+" ").lastIndexOf(" bar ");
    
    0 讨论(0)
提交回复
热议问题