I'm trying to find a relatively easy and reliable method to extract the base URL from a string variable using JavaScript (or jQuery).
For example, given something like:
http://www.sitename.com/article/2009/09/14/this-is-an-article/
I'd like to get:
http://www.sitename.com/
Is a regular expression the best bet? If so, what statement could I use to assign the base URL extracted from a given string to a new variable?
I've done some searching on this, but everything I find in the JavaScript world seems to revolve around gathering this information from the actual document URL using location.host or similar.
This works:
To get the origin of any url, including paths within a website (
/my/path
) or schemaless (//example.com/my/path
), or full (http://example.com/my/path
) I put together a quick function.In the snippet below, all three calls should log
https://stacksnippets.net
.A good way is to use JavaScript native api
URL
object. This provides many usefull url parts.For example:
As you can see here you can just access whatever you need.
For example:
console.log(urlObject.host); // "stackoverflow.com"
doc for URL
You can use below codes for get different parameters of Current URL
You then can use it like this...
The value of url will be...
The "var url" also contains two methods.
In this case the value of paramQ will be 1.
The value of allParameters will be the parameter names only.
Tested on IE,chrome and firefox.
You can do it using a regex :
does it fit ?