I have the full url in a javascript variable and I want to strip it down to the bare url.
For example:
.php,
strip down to:
www.google, youtube
How would I do this in javascript?
Thanks
This is not similar to the other links as I am doing this within a chrome extension, therefore the only way to get the url is using the chrome extension api which only provides the full url. As such I need to strip the full url
I have the full url in a javascript variable and I want to strip it down to the bare url.
For example:
https://www.google./hello/hi.php, http://youtube.
strip down to:
www.google., youtube.
How would I do this in javascript?
Thanks
This is not similar to the other links as I am doing this within a chrome extension, therefore the only way to get the url is using the chrome extension api which only provides the full url. As such I need to strip the full url
Share Improve this question edited Aug 11, 2015 at 12:41 kabeersvohra asked Aug 11, 2015 at 12:32 kabeersvohrakabeersvohra 1,0692 gold badges14 silver badges31 bronze badges 03 Answers
Reset to default 5You can try this:
\/\/([^\/,\s]+\.[^\/,\s]+?)(?=\/|,|\s|$|\?|#)
Regex live here.
Live JavaScript sample:
var regex = /\/\/([^\/,\s]+\.[^\/,\s]+?)(?=\/|,|\s|$|\?|#)/g;
var input = "https://www.google./hello/hi.php, http://youtube.,"
+ "http://test#jump or http://google.?q=test";
while (match = regex.exec(input)) {
document.write(match[1] + "<br/>");
};
Hope it helps
Use the global window.location.hostname
variable, and it will give you this information.
While parsing with regular expressions like the other answers suggest is possible, a better approach would be to use the URL()
object/API (docs).
const a = "https://www.google./hello/hi.php";
const hostname = new URL(a).hostname; // "www.google."
Apart from being arguably "cleaner", another advantage is that if the underlying parsing logic is incorrect, it is a (potentially security) bug in the browser, not your code, and will be likely fixed without your effort.