0

I need to remove everything before the third forward using regex so that for example https://stackoverflow.com/questions/ask becomes /questions/ask I'm not the greatest when it comes to regular expressions so your help would be much appreciated.

This is what I have so far https://regex101.com/r/qQ2dE4/498

The code I currently have is but want to use regex:

url.substring(url.indexOf('\/') + 3)
nless
  • 156
  • 3
  • 16
  • `url.indexOf('\/') + 3` wouldn't remove everything before the third / anyway - and your regex101 is not in javascript mode either – Jaromanda X Nov 04 '20 at 22:13
  • Try `s = s.replace(/^(?:[^\/]*\/){3}/, '/')` or check this: https://regex101.com/r/qQ2dE4/499 – anubhava Nov 04 '20 at 22:18

2 Answers2

1

Use this:

(?<=.*\/.*\/.*\/).+

Demo

Explanation:

  • (?<= - its positive look behind, in any position that's pattern inside it is find matching start from this position to forward.

  • .*\/.*\/.*\/ - it is used inside the positive look behind, it cause matching start after the position that behind that position is 3 forward slashes

  • .+ - match one or more of from anything

Edit: From @JaromandaX's comment, this can also be used (and honestly I think it more readable and simper):

(?<=(?:.*?\/){3}).+

Alireza
  • 2,103
  • 1
  • 6
  • 19
0

I understand the questions asks for regex but the need is unclear - if all you need is the path name there are better tools in the toolbox (for anybody not working on a homework exercise).

const url = 'https://stackoverflow.com/questions/ask'
console.log(new URL(url).pathname)
Emissary
  • 9,954
  • 8
  • 54
  • 65