Search code examples
javascriptregexfilenames

RegEx to extract text between last forwardslash and specific string (javascript)


I am trying to extract a specific string between the last forward slash and a dot without success. I tried the ones on this solution: R regex for everything between LAST backslash and last dot

Here is an example of the full string:

48494,Test,0000,Color,,,htps://url/test/testing/bb/1/dim/green.png

I want to extract "green", which is always between last slash and the last dot. I also tried the following regex:

([^\/]+$)

But this one selects everything after backslash. I want to remove everything after last dot in order to pick just the color.

EDIT: This question is different from Get Filename from URL and Strip File Extension because I am looking for a regex to use by the match method not replace.

I can't use replace, because the whole system is prepared to use match operator and can't be changed, since a lot of rules already exist for other scenarios using regex expression with match. The engine uses match, not replace.


Solution

  • You may use

    /[^\/]+(?=\.[^\/.]*$)/
    

    See the regex demo.

    Details

    • [^\/]+ - 1+ chars other than /
    • (?=\.[^\/.]*$) - a positive lookahead that requires . and then 0+ chars other than . and / to the end of the string immediately to the right of the current location. Since lookaheads are zero width assertions the text matched with the lookahead is not added to the overall match.

    Note that in JS code, you should mind the use of backslashes inside RegExp constructor and inside regex literals: use double backslashes inside the former and single backslashes in the latter, /a\/b\d/ = new RegExp("a/b\\d") (the slashes are not special regex metacharacters and need no escaping).

    JS demo:

    var s = "48494,Test,0000,Color,,,htps://url/test/testing/bb/1/dim/green.png";
    
    console.log(s.match(new RegExp("[^/]+(?=\\.[^/.]*$)")));
    console.log(s.match(/[^\/]+(?=\.[^\/.]*$)/));