Basque0407 Basque0407 - 14 days ago 5
Javascript Question

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.

Answer

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

Comments