skip to Main Content

I have the below urls :

https://comanage.example.edu/sp
https://wiki.cs.example.org/sp
https://intranet.math.example.edu/sp
https://myapp.example.com/sp

For these urls, I need to define a function that can detect them as URLs and then replace the https:// and sp path from them. Basically, I just need the hostname only.For ex, like below

https://comanage.example.edu/sp      ->comanage.example.edu
https://wiki.cs.example.org/sp       ->wiki.cs.example.org
https://intranet.math.example.edu/sp ->intranet.math.example.edu
https://myapp.example.com/sp         ->myapp.example.com

For non urls, the function should detect and do not replace for them. Like below,

nonurl.example.com -> ***no replacement*** 

Can anyone please suggest me a solution for above,I do not have much knowledge on usage of regex.

2

Answers


  1. The pattern ^https?:// should work here pretty easily for you. We can use that to replace http:// and https:// at the beginning of any string with an empty string

    In the pattern the ^ symbol denotes the beginning of the string. This means if http:// somehow appeared in the middle of the string, it would not match that since it must be at the beginning

    The ? marks the previous character as optional. In the pattern the s is optional to that http and https can be found.

    The / is there simply because the slashes have to be escaped.

    const urls = [
      'https://comanage.example.edu/sp',
      'https://wiki.cs.example.org/sp',
      'https://intranet.math.example.edu/sp',
      'https://myapp.example.com/sp',
      'nonurl.example.com',
    ];
    
    const pattern = /^https?:///i;
    
    urls.forEach(u => {
      console.log(u, '-->', u.replace(pattern, ''));
    });
    Login or Signup to reply.
  2. Simply use URL API

    [ 'https://comanage.example.edu/sp'
    , 'https://wiki.cs.example.org/sp'
    , 'https://intranet.math.example.edu/sp'
    , 'https://myapp.example.com/sp' 
    ]
    .forEach( url => console.log( new URL(url).host ) );
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search