1

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.

3

3 Answers 3

4

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.

1

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);

0
0

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.