-3

Given a full URI string I want to return only the protocol and domain name. For example:

sometodo("http://127.0.0.1:8000/hello/some/word1212/") 
// return: http://127.0.0.1 
    
sometodo("http://127.0.0.1:8000/hello/some/valorant_operator/") 
// return: http://127.0.0.1

How can I remove the third / and the following information from the string?

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
touchingtwist
  • 1,930
  • 4
  • 23
  • 38
  • Please show us what you have tried. Also you should be able to find many answers to this if you just search a bit, since this has been answered many times before. – Carsten Løvbo Andersen Aug 04 '20 at 09:01
  • 1
    jQuery is a framework primarily for amending the DOM. To manipulate strings you just need plain old JS – Rory McCrossan Aug 04 '20 at 09:02
  • 2
    Does this answer your question? [Get protocol, domain, and port from URL](https://stackoverflow.com/questions/6941533/get-protocol-domain-and-port-from-url) – n9iels Aug 04 '20 at 09:05

2 Answers2

2

If it's going to be URLs then work with it as you would with an URL. No need to parse/regex/substring, just make an URL object and access its values.

https://developer.mozilla.org/en-US/docs/Web/API/URL

const url = new URL("http://127.0.0.1:8000/hello/some/word1212/");
let result = `${url.protocol}//${url.host}`;
Dropout
  • 13,653
  • 10
  • 56
  • 109
0

    sometodo("http://127.0.0.1:8000/hello/some/word1212/");
    sometodo("http://127.0.0.1:8000/hello/some/valorant_operator/");
    
    function sometodo(str) {        
        var output = str.match(/^(?:[^\/]*\/){3}/)[0];
        console.log(output);
        return output;
    }
Andrew Arthur
  • 1,563
  • 2
  • 11
  • 17