Convert any URL into a relative URL [duplicate] - javascript

I want to get the relative URL from an absolute URL in JavaScript using regex and the replace method.
I tried the following but it is not working:
var str="http://localhost/mypage.jsp";
document.write(str.replace("^[\w]*\/\/[\w]*$",""));

A nice way to do this is to use the browser's native link-parsing capabilities, using an a element:
function getUrlParts(url) {
var a = document.createElement('a');
a.href = url;
return {
href: a.href,
host: a.host,
hostname: a.hostname,
port: a.port,
pathname: a.pathname,
protocol: a.protocol,
hash: a.hash,
search: a.search
};
}
You can then access the pathname with getUrlParts(yourUrl).pathname.
The properties are the same as for the location object.

Below snippet returns the absolute URL of the page.
var myURL = window.location.protocol + "//" + window.location.host + window.location.pathname;
If you need only the relative url just use below snippet
var myURL=window.location.pathname;
Checkout get relative URL using Javascript for more details and multiple ways to achieve the same functionality.

If by "relative URL" you mean the part of the string after the first single /, then it's simple:
document.write(str.replace(/^(?:\/\/|[^/]+)*\//, ''));
This matches all the characters up to the first single / in the string and replaces them with the empty string.
In: http://localhost/my/page.jsp --> Out: /my/page.jsp

const url = new URL('https://www.example.com/path/#anchor?query=value');
const rel = url.toString().substring(url.origin.length)
console.log(rel)
// Output: /path/#anchor?query=value

Don't use low-level stuff like regexp etc. These things have been solved by so many other people. Especially the edge cases.
Have a look at URI.js, it should do the job: http://medialize.github.io/URI.js/docs.html#relativeto
var uri = new URI("/relative/path");
// make path relative
var relUri = uri.relativeTo("/relative/sub/foo/sub/file"); // returns a new URI instance
// relUri == "../../../path"

URL.getRelativeURL
There's an public-domain extension for the standard URL object called getRelativeURL.
It's got a few cool tweaks like force reload, you should check it out!
Try it live.       View on Gist.
Example usage
//syntax: <URL to convert>.getRelativeURL(<relative to this URL>)
//link from Mypage to Google
a = new URL("https://google.com/search");
a.getRelativeURL("https://mypage.com")
== "//google.com/search";
//link from the current location.href
a.getRelativeURL();
//link from Olutsee to Polk
var from = new URL("http://usa.com/florida/baker/olutsee");
var to = new URL("http://usa.com/florida/polk");
to.getRelativeURL(from) == "../../polk";

don't forget that \ is an escape character in strings, so if you would like to write regex in strings, ensure you type \ twice for every \ you need. Example: /\w/ → "\\w"

Below you can find script on that here we have only one problem which is one manual work, we want to add split attribute ie, if your site link is: Get relative URL from absolute URL
we want to url as below:
/questions/6263454/get-relative-url-from-absolute-url
so in below code we have to add .com instead of .net ie,
var res = at.split(".net"); here we want to add as per our requirement now i need to seperate after .com so code will be "var res = at.split(".com");".
i think you guys got that point if you have still doubt let me know please
and to see changes in code by inspecting:
$(document).ready(function(){
$("a").each(function(){
var at= $(this).attr("href");
var res = at.split(".net");
var res1 = res[0];
var res2 = res[1];
alert(res2);
$(this).attr("href",res2);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="banner-message">
<p>Hello World</p>
Change color
</div>
<div id="banner-message">
<p>Hello World</p>
Change color
</div>

Related

Rewrite URL Prefix Using Javascript / Jquery

I am retrieving some data from an external API using javascript, I'm then displaying this data on a HTML page.
Within this returned data is a URL, it's in the following format;
var url = https://img.evbuc.com/moreStuff
I need to rewrite this URL so that it's prefixed with www, like this;
var url = https://www.img.evbuc.com/moreStuff
I want to achieve this using either javascript or jquery.
How can I achieve this? An explanation of the correct code would be great too.
You don't need regex for this you can simply use URL api
let url = "https://img.evbuc.com/moreStuff"
let parsed = new URL(url)
parsed.host = parsed.host.startsWith('www.') ? parsed.host : "www."+ parsed.host
console.log(parsed)
You can use a regular expression to search and replace.
Following example also works with:
http://img.evbuc.com/moreStuff
//img.evbuc.com/moreStuff
https://img.evbuc.com/moreStuff//someMoreStuff
function prependUrl(url) {
return url.replace(/^([^\/]*)(\/\/)(.*)/, '$1//www.$3');
}
const urls = [
'https://img.evbuc.com/moreStuff',
'http://img.evbuc.com/moreStuff',
'//img.evbuc.com/moreStuff',
'https://img.evbuc.com/moreStuff//someMoreStuff'
];
urls.forEach((url) => console.log(`${ url } -> ${ prependUrl(url) }`));
The regular expression contains 3 capturing groups:
Select everything up to the first / (excluding)
Select the // (for protocol root)
Select the rest
The replacement value takes everything up to the first / (which may be an empty string as well)
Replace the // with //www.
Append the rest
If you want something that will work with any protocol, try this regex:
var url = "https://img.evbuc.com/moreStuff"
var new_url = url.replace(/^([a-zA-Z][a-zA-Z0-9\.\+\-]*):\/\//, "$1://www.")
console.log('new URL: ', new_url)
Simple string operations:
var url = 'https://img.evbuc.com/moreStuff'
var newUrl = url.split('//')[0] + '//www.' + url.split('//')[1]
console.log(newUrl)
and yet another way to do this is like this:
var url = 'https://img.evbuc.com/moreStuff'
var newUrl = url.replace('https://', 'https://www.')
console.log(newUrl)

Display the last part of URL javascript?

I need to display the last part of a URL using javascript!
I am using this code but this will display the entire URL:
<script language="javascript">
document.writeln(document.location);
var url = $(this).attr("href");
var part = url.substring(url.lastIndexOf('/') + 1);
</script>
if the URL look like this:
domain.com/something/file
i need to only display the "file".
The reason document.write(window.location) writes the location is because of the toString method of window.location, which really returns window.location.href.
// This will fallback to the location.pathname if this
// is not the location already or not an anchor.
var path = this.pathname || window.location.pathname;
var part = path.split('/').pop();
Pathname is everything after the domain name. So, http://example.com/something/file breaks down like this:
protocol: http:
hostname: example.com
pathname: something/file
href: http://example.com/something/file
(there is also port, search (?this=that) and hash (#hash), which would both be empty in this case)
So, I'm taking something/file and splitting it into an array wherever this is a /, which would be ["something", "file"]
After that I'm popping off the last part of the array, in this case "file"
Both window.location and any <a> tag have these properties. So, if you need to parse a URL, you can do the following in javascript:
var anchor = document.createElement('a');
anchor.href = '/about'; // this could be any relative or absolute url
And now anchor will have the all those properties if you need them. No need for a regex or anything.
UPDATE
In newer browsers (excluding IE unless you use url-polyfill), you can use URL instead of an <a /> like so:
const url = new URL('/about', this.location)
// or if you don't care about the host, you can do the following
// const url = new URL('http://localhost/about')
This contains all the other information, plus url.searchParams, which makes it so you don't have to parse the search string yourself either.
<script type="text/javascript">
var segment_str = window.location.pathname; // return segment1/segment2/segment3/segment4
var segment_array = segment_str.split( '/' );
var last_segment = segment_array.pop();
document.write(last_segment); // alerts segment4
</script>
JsFiddle: http://jsfiddle.net/HNMV3/1/
var pathname = window.location.pathname,
part = pathname.substr(pathname.lastIndexOf('/') + 1);
replace(/-/g," ") and split(".html") will remove "hyphens" and ".html" from url,thus only keeping the path name only
var parts=window.location.pathname.split("/");
var query=parts[parts.length-1].split(".html");
query[0]=query[0].replace(/-/g," ");
document.write(query[0])

Get absolute path in javascript

Can you get the absolute path in html.
If i use location.href i can get the url but how can i trim the filename.html ?
IS there a better way to get the path.
Thanks!
location.pathname gives you the local part of the url.
var filename = location.pathname.match(/[^\/]+$/)[0]
The above gives you only the very last part. For example, if you are on http://somedomain/somefolder/filename.html, it will give you filename.html
For this page if you inspect the window.location object you will see
hash:
host: stackoverflow.com
hostname: stackoverflow.com
href: http://stackoverflow.com/questions/8401879/get-absolute-path-in-javascript
pathname: /questions/8401879/get-absolute-path-in-javascript
port:
protocol: http:
search:
Documentation at MDN
So location.pathname is what you want. And if you want to extract the last part use regex.
var lastpart = window.location.pathname.match(/[^\/]+$/)[0];
var full = location.pathname;
var path = full.substr(full.lastIndexOf("/") + 1);
Or if you need everything from protocol to last '/' you can use:
new RegExp('[^?]+/').exec(location.href)
and don't worry that it will match to the first '/' because '+' is a greedy quantifier, which means it will match as much as it can. First part '[^?]' is to stop matching before parameters because '/' can appear in parameter values like t.php?param1=val1/val2.
Try this:
var loc = window.location.href;
var fileNamePart = loc.substr(loc.lastIndexOf('/') + 1);
// "http://localhost:8080/public/help/index.html"
const loc = window.location.href;
// "http://localhost:8080/public/help/"
const path = loc.substr(0, loc.lastIndexOf('/') + 1);

Javascript remove characters utill 3 slash /

Whats the best to way, based on the input below, to get everything in the url after the domain:
var url = "http://www.domain.com.uk/sadsad/asdsadsad/asdasdasda/?asda=ggy";
var url = "http://www.domain.com.uk/asdsadsad/asdasdasda/#45435";
var url = "http://www.domain.com.uk/asdasdasda/?324324";
var url = "http://www.domain.com.uk/asdasdasda/";
The output:
url = "/sadsad/asdsadsad/asdasdasda/?asda=ggy";
url = "/asdsadsad/asdasdasda/#45435";
url = "/asdasdasda/?324324";
UPDATE: the domain its not always the same. (sorry)
Thx
You should really parse the URI.
http://stevenlevithan.com/demo/parseuri/js/
Every absolute URL consists of a protocol, separated by two slashes, followed by a host, followed by a pathname. An implementation can look like:
// Search for the index of the first //, then search the next slash after it
var slashOffset = url.indexOf("/", url.indexOf("//") + 2);
url = url.substr(slashOffset);
If the domain is always the same, a simple replace will work fine:
var url = "http://www.domain.com.uk/sadsad/asdsadsad/asdasdasda/?asda=ggy";
var afterDomain = url.replace("^http://www.domain.com.uk/", "");
You could also use RegEx:
var url = "http://www.domain.com.uk/sadsad/asdsadsad/asdasdasda/?asda=ggy";
var afterDomain = url.replace(/^[^\/]*(?:\/[^\/]*){2}/, "");
Assuming this is in the browser, creating an anchor element will do a lot of magic on your behalf:
var a=document.createElement('a');
a.href="http://somedomain/iouhowe/ewouho/wiouhfe?jjj";
alert(a.pathname + a.search + a.hash); // /iouhowe/ewouho/wiouhfe?jjj

taking off the http or https off a javascript string

I have the following strings
http://example.com
https://example.com
http://www.example.com
how do i get rid of the http:// or https://?
Try with this:
var url = "https://site.com";
var urlNoProtocol = url.replace(/^https?\:\/\//i, "");
You can use the URL object like this:
const urlWithoutProtocol = new URL(url).host;
You may use URL() constructor. It will parse your url string and there will be an entry w/o protocol. So less headache with regexps:
let u = new URL('https://www.facebook.com/companypage/');
URL {
hash: ""
host: "www.facebook.com"
hostname: "www.facebook.com"
href: "https://www.facebook.com/companypage/"
origin: "https://www.facebook.com"
password: ""
pathname: "/companypage/"
port: ""
protocol: "https:"
search: ""
searchParams: URLSearchParams {}
username: ""
}
u.host // www.facebook.com
u.hostname // www.facebook.com
Although URL() drops out a protocol, it leaves you with www part. In my case I wanted to get rid of that subdomain part as well, so had to use to .replace() anyway.
u.host.replace(/^www./, '') // www.facebook.com => facebook.com
var txt="https://site.com";
txt=/^http(s)?:\/\/(.+)$/i.exec(txt);
txt=txt[2];
for parsing links without http/https use this:
var txt="https://site.com";
txt=/^(http(s)?:\/\/)?(.+)$/i.exec(txt);
txt=txt[3];
var str = "https://site.com";
str = str.substr( str.indexOf(':') + 3 );
Instead of .substr(), you could also use .slice() or .substring(). They'll all produce the same result in this situation.
str = str.slice( str.indexOf(':') + 3 );
str = str.substring( str.indexOf(':') + 3 );
EDIT: It appears as though the requirements of the question have changed in a comment under another answer.
If there possibly isn't a http:// in the string, then do this:
var str = "site.com";
var index = str.indexOf('://');
if( index > -1 )
str = str.substr( index + 3 );
This answer extends some answers above, http://, https://, or // which is also common.
Thanks for answers above that led me to this!
const urls = [ "http://example.com", "https://example.com", "//example.com" ]
// the regex below states: replace `//` or replace `//` and the 'stuff'
const resolveHostNames = urls.map(url => url.replace(/\/\/|.+\/\//, ''))
console.log(resolveHostNames);
Here's a link to a codepen.
Strip the protocol from a URL:
var url = "https://site.com";
var urlNoProto = url.split('/').slice(2).join('/');
Works with any protocol, ftp, http, gopher, nntp, telnet, wais, file, prospero ... all those specified in RFC 1738 with the exception of those without a // in them (mailto, news).
Please note that in real web pages inherited protocol // is a common practice https://paulirish.com/2010/the-protocol-relative-url.
So I suggest regexp covering this case as well:
/^\/\/|^https?:\/\//
(you can optimize it)
Another efficient solution,
url.replace(/(^(\w+:)?\/\//, '')
Assuming there are no double slashes other than the protocol, you could do:
var url = "https://example.com";
var noProtocol = url.split('//')[1];
You may use HTMLHyperlinkElementUtils of DOM:
function removeProtocol(url) {
const a = document.createElement('a');
a.href = url;
// `url` may be relative, but `a.href` will be absolute.
return a.href.replace(a.protocol + '//', '');
}
removeProtocol('https://example.com/https://foo');
// 'example.com/https://foo'
removeProtocol('wrong://bad_example/u');
// 'bad_example/u'
From HTMLHyperlinkElementUtils on MDN:
a.hostname, example.com
a.host, example.com:3000
a.pathname, /foo/bar.html
a.search, ?a=1&b=2
a.hash, #goo
a.username, a.password, a.port, etc.
Using regex might be an overkill when there's a handy native URL interface that does the job for you in 2 lines:
let url = "https://stackoverflow.com/questions/3999764/taking-off-the-http-or-https-off-a-javascript-string";
let a = new URL(url);
let withoutProtocol = a.host+a.pathname;
console.log(`Without protocol: ${withoutProtocol}`);
console.log(`With protocol: ${url}`);
URL API Support in browsers
Javascript use of split function also dervies the solution.
Awesome !!!
var url = "https://example.com";
url = url.split("://")[1]; // for https use url..split("://")[0];
console.log(url);

Categories

Resources