RegEx - Get All Characters After Last Slash in URL

后端 未结 8 2142
无人共我
无人共我 2020-11-29 07:00

I\'m working with a Google API that returns IDs in the below format, which I\'ve saved as a string. How can I write a Regular Expression in javascript to trim the string to

相关标签:
8条回答
  • 2020-11-29 07:31

    Don't write a regex! This is trivial to do with string functions instead:

    var final = id.substr(id.lastIndexOf('/') + 1);
    

    It's even easier if you know that the final part will always be 16 characters:

    var final = id.substr(-16);
    
    0 讨论(0)
  • 2020-11-29 07:31

    this regexp: [^\/]+$ - works like a champ:

    var id = ".../base/nabb80191e23b7d9"
    
    result = id.match(/[^\/]+$/)[0];
    
    // results -> "nabb80191e23b7d9"
    
    0 讨论(0)
  • 2020-11-29 07:38

    Just in case someone else comes across this thread and is looking for a simple JS solution:

    id.split('/').pop(-1)

    0 讨论(0)
  • 2020-11-29 07:44

    A slightly different regex approach:

    var afterSlashChars = id.match(/\/([^\/]+)\/?$/)[1];
    

    Breaking down this regex:

    \/ match a slash
    (  start of a captured group within the match
    [^\/] match a non-slash character
    + match one of more of the non-slash characters
    )  end of the captured group
    \/? allow one optional / at the end of the string
    $  match to the end of the string
    

    The [1] then retrieves the first captured group within the match

    Working snippet:

    var id = 'http://www.google.com/m8/feeds/contacts/myemail%40gmail.com/base/nabb80191e23b7d9';
    
    var afterSlashChars = id.match(/\/([^\/]+)\/?$/)[1];
    
    // display result
    document.write(afterSlashChars);

    0 讨论(0)
  • 2020-11-29 07:47

    Don't know JS, using others examples (and a guess) -

    id = id.match(/[^\/]*$/); // [0] optional ?

    0 讨论(0)
  • 2020-11-29 07:47

    Why not use replace?

    "http://google.com/aaa".replace(/(.*\/)*/,"")
    

    yields "aaa"

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