0

i got two kinds of urls:

http://somedomain/somepath/DP/vk3103s3/ref/somepath
http://somedomain/somepath/DP/vk3103s3

and try to math the path between '/DP/' to '/ref' or to the end of the url(if there is no '/ref' exists in the url). in the example url mentioned above should return a string 'vk3103s3'.

and i try to using a regex like: new RegExp('/dp/(.*)(?:/ad|\$)', 'i');
it doesn't work. could somebody help to get it and tell why...

1 Answers1

0

After the /DP/, match anything but a slash:

[
  'http://somedomain/somepath/DP/vk3103s3/ref/somepath',
  'http://somedomain/somepath/DP/vk3103s3'
].forEach(str => {
  console.log(
    str.match(/\/dp\/([^/]+)/i)[1]
  );
});

(also, don't use new RegExp unless you need to dynamically create a pattern from a variable - you'll have to double-escape the \s. Better to use a regular expression literal)

If there can be multiple /-separated sections of the URL between the DP and the /ref, then similar to what you're doing now, lazy-repeat, and lookahead for \/ref|$. Don't use \$, because that would match a literal $ character, rather than the end of the line:

[
  'http://somedomain/somepath/DP/vk3103s3/ref/somepath',
  'http://somedomain/somepath/DP/vk3103s3',
  'http://somedomain/somepath/DP/vk3103s3/somethingElse/ref/somepath'
].forEach(str => {
  console.log(
    str.match(/\/dp\/(.*?)(?=\/ref|$)/mi)[1]
  );
});
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320