Basque0407
Basque0407

Reputation: 59

Get protocol, hostname, and path from URL

I have made a Regular expression that captures the Short URL of a link. For example:

https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=picture%20of%20a%20potato

My regular expression would be:

/(https:\/\/.+?)\/.+/

Now this would only capture:

https://www.google.com

What I want to do now is store the captured RegEx into a variable. Any help or suggestions are greatly appreciated.

Upvotes: 1

Views: 2777

Answers (3)

SLePort
SLePort

Reputation: 15461

Your regex won't capture https://www.google.com.

Use capturing group and apply your regex with regex.exec(). Then access the returned array to set your variable:

str="https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=picture%20of%20a%20potato";
regex = new RegExp('(https?://.*?\)/');
match = regex.exec(str)[1];
console.log(match);

Upvotes: 1

000
000

Reputation: 27247

The <a> DOM element provides this sort of splitting of hrefs for you! Here is how:

var a = document.createElement('a');
a.href = 'https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=picture%20of%20a%20potato';
console.log({
        protocol: a.protocol,
        host: a.host,
        hostname: a.hostname,
        port: a.port,
        pathname: a.pathname,
        search: a.search
});

returns:

{
  "protocol": "https:",
  "host": "www.google.com",
  "hostname": "www.google.com",
  "port": "",
  "pathname": "/webhp",
  "search": "?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8"
}

See https://www.abeautifulsite.net/parsing-urls-in-javascript for more information.

Upvotes: 4

Pointy
Pointy

Reputation: 413737

You don't need the "g" flag, so it'd be

var matchResult = someUrlString.match(/(https?:.*?\.{1,3})/i);

Then matchResult would be an array (or null). If not null, your regex would result in indexes 0 and 1 both containing the matched text.

Your regular expression, for the record, matches things like

  • http:foo.
  • https:zimbabwe_is_nice...
  • http:Hello my name is Adam and have you considered aluminum siding? It can save you thousands in upkeep costs.

Upvotes: 0

Related Questions