0

I am trying to replace all parts before youtube.com in a URL with nothing, but my regex expression seems to do nothing.

For example:

https://www.youtube.com/watch?v=k5iJV2cYCt8 -> youtube.com/watch?v=k5iJV2cYCt8
http://www.youtube.com/watch?v=k5iJV2cYCt8 -> youtube.com/watch?v=k5iJV2cYCt8
www.youtube.com/watch?v=k5iJV2cYCt8 -> youtube.com/watch?v=k5iJV2cYCt8

function setYoutubeUrl(youtubeUrl: string) {
    return youtubeUrl.replace(
      /((\/+|https??:\/\/)?(www\.)?(?=youtube\.com\/.+\/.)|(?<=youtube\.com\/.+\/.)\/*([?#].*)?)/gi,
      ''
    );
}

console.log(setYoutubeUrl("https://www.youtube.com/watch?v=k5iJV2cYCt8"));

1
  • Consider using URL and grab the appropriate properties. The only thing you should need to remove is "www." that way. Commented Apr 15, 2021 at 12:37

1 Answer 1

1

Try to use the regex /^(?:https?:\/\/)?(?:www\.)?/i. So your function will be like this:

function setYoutubeUrl(youtubeUrl) {
    return youtubeUrl.replace(
      /^(?:https?:\/\/)?(?:www\.)?/i,
      ''
    );
}

Regex Explanation:

  • ^ asserts position at start of the string
  • Non-capturing group (?:https:\/\/)?
    • ? matches the previous token between zero and one times, as many times as possible, giving back as needed (greedy)
    • http matches the characters http literally (case insensitive)
      • s matches the character s literally (case insensitive)
      • ? matches the previous token between zero and one times, as many times as possible, giving back as needed (greedy)
    • : matches the character : literally (case insensitive)
    • \/ matches the character / literally (case insensitive)
    • \/ matches the character / literally (case insensitive)
  • Non-capturing group (?:www\.)?
    • ? matches the previous token between zero and one times, as many times as possible, giving back as needed (greedy)
    • www matches the characters www literally (case insensitive)
    • \. matches the character . literally (case insensitive)
  • Global pattern flags
    • i modifier: insensitive. Case insensitive match (ignores case of [a-zA-Z])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.