I need to write some javascript to strip the hostname:port part from a url, meaning I want to extract the path part only.
i.e. I want to write a function getPath(url) such that getPath(“http://host:8081/path/to/something”) returns “/path/to/something”
Can this be done using regular expressions?
Quick ‘n’ dirty:
Everything after the hostname and port (including the initial /) is captured in the first group.
This regular expression seems to work: (http://[^/])(/.)
As a test I ran this search and replace in a text editor:
It converted this this text:
into this:
and converted this:
into this:
RFC 3986 ( http://www.ietf.org/rfc/rfc3986.txt ) says in Appendix B
The following line is the regular expression for breaking-down a well-formed URI reference into its components.
The numbers in the second line above are only to assist readability; they indicate the reference points for each subexpression (i.e., each paired parenthesis). We refer to the value matched for subexpression as $. For example, matching the above expression to
results in the following subexpression matches:
where
<undefined>
indicates that the component is not present, as is the case for the query component in the above example. Therefore, we can determine the value of the five components asI know regular expressions are useful but they’re not necessary in this situation. The Location object is inherent of all links within the DOM and has a pathname property.
So, to access that property of some random URL you could need to create a new DOM element and then return its pathname.
An example, which will ALWAYS work perfectly:
jQuery version: (uses regex to add leading slash if needed)
The window.location object has pathname, search and hash properties which contain what you require.
for this page
so you could use
It’s very simple:
Trying to find second occurance of “:” followed by number and preceded by http or https.
This works for below two cases
Ex:
http://localhost:8080/myapplication
https://localhost:8080/myapplication
Hope this helps.