Skip to content
Advertisement

Regex to get last part of url without appended version and parameters

Hi guys I’ve got a very specific request where I would like to get the last part of a url without the parameters but if the name of the script has a version appended, like -V2, where the 2 could be any number, the regex would ignore it.

So far I found this (?!/)(w+)(?=.js) but it is only getting a single word.

Some examples:

https://s3.amazon-aws.com/bob.success.com/scripts/sampleScript-V2.js?x=123&name=bo-b https://s3.amazon-aws.com/bob.success.com/scripts/sampleScript.js?x=123&name=bo-b https://s3.amazon-aws.com/bob.success.com/scripts/sampleScript.js https://s3.amazon-aws.com/bob.success.com/scripts/sampleScript-v2.js

All should match sampleScript

Advertisement

Answer

//((.(?!/))+?)(-vd|).js/i
  • / matches the character /

  • 1st Capturing Group ((.(?!/))+?)

    • 2nd Capturing Group (.(?!/))+?

      . matches any character

      +? matches the previous token between one and unlimited times, as few times as possible, expanding as needed (lazy)

      Negative Lookahead (?!/) Assert that the Regex below does not match : / matches the character /

  • 3rd Capturing Group (-vd|)

    • 1st Alternative

      -v matches the characters -v d matches a digit (equivalent to [0-9])

    • 2nd Alternative

      null, matches any position

  • . matches the character .

  • js matches the characters js

  • Global pattern flags i modifier: insensitive. Case insensitive match (ignores case of [a-zA-Z])

const urls = [
  'https://s3.amazon-aws.com/bob.success.com/scripts/sampleScript-V2.js?x=123&name=bo-b',
  'https://s3.amazon-aws.com/bob.success.com/scripts/sampleScript.js?x=123&name=bo-b',
  'https://s3.amazon-aws.com/bob.success.com/scripts/sampleScript.js', 
  'https://s3.amazon-aws.com/bob.success.com/scripts/sampleScript-v2.js'
];

const regexp = //((.(?!/))+?)(-vd|).js/i;

urls.forEach(url => console.log(regexp.exec(url)[1]));
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement