taking off the http or https off a javascript string - javascript

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

Related

Convert any URL into a relative URL [duplicate]

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>

javascript for splitting url and removing last part

http://www.google.com/site!#656126.72367
In this url, how to split and remove the part from exclamatory mark when page loaded using JS.
I just want http://www.google.com/site
Use string replace method , match every character after ! with regular expression and replace with ""
var url = 'http://www.google.com/site!#656126.72367';
url = url.replace(/!.*/,"");
You could use:
var host = window.location.hostname; // will be www.google.com
var path = window.location.pathname; // will be /site
In the end, you will have:
var url = "http://" + host + path;
Note: you can also use window.location.protocol, which in this case is http::
var url = window.location.protocol + '//' + host + path;
Update: as suggested by Rajesh, the window.location object also has access to the hash:
var hash = window.location.hash; // will be 656126.72367
It might be useful to do a console.log(window.location) and see what's in there!
This method works even if the hash contains several ! or #
var url = 'http://www.google.com/site!#656126.72367';
url = url.substring(0, url.indexOf('!'));
document.write(url);
substring extracts the characters from a string, between two specified indices (in this case on the first occurence and then on !), and returns the new sub string.
jsFiddle demo
var url = "http://www.google.com/site!#656126.72367";
url = url.split('!')[0];
console.log(url);

How do I replace the port number in JavaScript?

I have an array of strings, and I want to create a new array which contains the same strings without port numbers (the port number is a ":" followed by a number). For example if the string is "http://www.example.com:8080/hello/" Then it should be replaced with "http://www.example.com/hello/". How do I do it in JavaScript? I need it to call safari.extension.addContentScriptFromURL because the whitelist can't contain port numbers. If possible, it's better to replace the port number only between the second and third slash and leave the rest of the string unchanged.
You don't need any library or REGEX
https://developer.mozilla.org/en-US/docs/Web/API/URL
var url = new URL('http://localhost:8080');
url.port = '';
console.log(url.toString());
Regrards
One quite nifty way to do this, is to create an a element, and assign the URL you have as href - because the HTMLAnchorElement interface implements URLUtils, and therefor supports accessing the individual parts of the address in the same way the location object does, and you can set them individually as well:
var foo = document.createElement("a");
foo.href = "http://www.example.com:8080/hello/";
foo.port = ""
var newURL = foo.href;
console.log(newURL); // output: http://www.example.com/hello/
http://jsfiddle.net/pdymeb5d/
This should probably do what you want:
var newUrls = urls.map(function (url) {
return url.replace(/([a-zA-Z+.\-]+):\/\/([^\/]+):([0-9]+)\//, "$1://$2/");
});
Edit: It seems the schema part of URIs can contain "+", "." and "-" also. Changed the regular expression accordingly.
See: https://en.wikipedia.org/wiki/URI_scheme
You can use regex with string.replace() as follows,
var text = "http://www.example.com:8080/hello/";
var withNoDigits = text.replace(/[0-9]/g, '');
var outputString = withNoDigits.replace(/:([^:]*)$/,'$1');
alert(outputString);
function parseURL(url) {
var parser = document.createElement('a'),
searchObject = {},
queries, split, i;
parser.href = url;
queries = parser.search.replace(/^?/, '').split('&');
for( i = 0; i < queries.length; i++ ) {
split = queries[i].split('=');
searchObject[split[0]] = split[1];
}
return {
protocol: parser.protocol,
host: parser.host,
hostname: parser.hostname,
port: parser.port,
pathname: parser.pathname,
search: parser.search,
searchObject: searchObject,
hash: parser.hash
};
}
Use this to parse any URL and arrange in a format you prefer.
OK, I used your answer and changed it a little, because the protocol may contain dashes too:
var newUrls = urls.map(function(url) {
return url.replace(/([^\/\:]+):\/\/([^\/]+):([0-9]+)\//, "$1://$2/");
})
I have found best solution here.
var url = 'http://localhost:7001/www.facebook.com';
// Create a regex to match protocol, domain, and host
var matchProtocolDomainHost = /^.*\/\/[^\/]+:?[0-9]?\//i;
// Replace protocol, domain and host from url, assign tomyNewUrl
var myNewUrl = url.replace(matchProtocolDomainHost, '');
Now myNewUrl === 'www.facebook.com'.
Better to read full page.
remove hostname and port from url using regular expression

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

Categories

Resources