Javascript conditional replace not working - javascript

Javascript conditional replace image src to https if url prefix is in http:// and ignore https:// currently i have this piece of code added to the source part.
Javascript:
src="' + p.replace("http","https") + '"
The issue:
http:// gets replace to https:// but the problem is its also replacing https:// to httpss:// which is breaking the src attribute and images are returning 404 error.
How to fix this issue?
UPDATE:
The variable p contains image URL which is sometimes http and sometimes its https. the above code replaces http to https successfully but when a url have https it adds another s like this httpss:// which returns 404 and image cant load

Just expand the selection, so that you are replacing http:// instead of just http, i.e.:
p.replace("http://", "https://")
See example below:
const urls = [
'https://example.com',
'http://example.com'
];
urls.forEach(url => {
console.log(`Original URL: ${url}`);
// Incorrect behavior
console.log(url.replace('http', 'https'));
// Correct behavior
console.log(url.replace('http://', 'https://'));
});
An alternative way to solve this problem will be to leverage the URL API, which is supported by anything after IE11. You simply parse your string using the new URL() constructor, and then modify its protocol property, i.e.:
const urls = [
'https://example.com',
'http://example.com'
];
urls.forEach(url => {
console.log(`Original URL: ${url}`);
const modifiedUrl = new URL(url);
modifiedUrl.protocol = 'https';
console.log(modifiedUrl.toString());
});

It is working fine. But could you please define your code why you add double quotes?
var p = 'http://google.com';
var src= p.replace("http","https");
console.log(src);
UPDATED
Please have a look to this updated solution.
var p = prompt('Enter URL?');
let str = p.split("://")[0];
var src= str === 'http' ? p.replace("http","https") : p;
console.log(src);

It doesn't work because your match string, http, is a subset of your replace string, https. So you need to suggest not to match https strings, or you could say match only http that doesn't have an s after it.
const urlVariants = [
'http://www.google.com',
'https://www.google.com'
]
urlVariants.forEach(url=> {
console.log( url, '->', url.replace('http:','https:') )
console.log( url, '->', url.replace(/http([^s])/,"https$1") )
})

You should match using regular expression. The regular expression to check if the url has uses http is :
/http[^(?=s)]{0}/i
Below is the working snippet to replace http by https successfully.
"http://www.google.com".replace(/http[^(?=s)]{0}/i,'https')

Related

Unexpected URL generated while using window.location.hostname

I am trying to append URL, but it the generated URL is not as expected. Below is the code that I've tested and its outcome.
Since I'm using a local server to test my system, the desired request URL is http://127.0.0.1:8000/api/posts. I will be deploying this system to a remote server in the near future so I cannot use the request URL as it is now. Base on the code below, what I am trying to do is to get the current hostname and append it with the route URL but it produces weird URL. How to solve this?
Component
created() {
var test = window.location.hostname + '/api/posts';
this.axios.get(test).then(response => {
this.posts = response.data.data;
});
Route Api (api.php)
Route::get('/posts', 'PostController#index');
Just use an absolute URL in your axios requests if you don't want to have to configure a base URL:
this.$axios.get('/apiposts')
Where the prefixed / is the important part.
You probably do not need to set baseURL. Have you tried to define baseURL? For example:
axios.get(`${process.env.HOST}:${PORT}/api/categories`)
Add this code in your: /src/main.js
const baseURL = 'http://localhost:8080';
if (typeof baseURL !== 'undefined') {
Vue.axios.defaults.baseURL = baseURL;
}
See the solution here Set baseURL from .env in VueAxios
I think in your app baseURL is set to http://127.0.0.1:8000 (default) and you append the host to this url in this line var test = window.location.hostname + '/api/posts';. Try it without this.

Will 'http:url' work for all browsers and devices?

In making a function that validates a user URL and prepends http: at the front, I have to take cases of www, https and // into account as being valid urls. The way I have it written now (see below), I only prepend http: , so that cases of //stackoverflow.com don't turn into http: ////stackoverflow.com.
This means that a url like stackoverflow.com becomes http:stackoverflow.com.
In Firefox and Chrome, this works just fine, but these URLS will be clicked from a variety of browsers and devices. Is it something that'll work universally? It'll be easy to rewrite this check for a // case, but I'm interested in the answer.
Prepend method:
function prependHTTPtoWebURL() {
var url = (el('org_website').value);
var httpVar;
var testFor;
if (url) {// If there's a website URL value
testFor = url.toLowerCase();
if (testFor.indexOf("http") != 0){
httpVar = 'http:'; //add it
url = httpVar + url;
el('org_website').value = url;
}
}
}
Try playing with regex. Check this code for instance:
var someurl = "www.google.com";
var otherurl = "google.com";
var anotherurl = "//google.com";
function prependHTTPtoWebURL(url) {
var newurl = url.replace(/^(http)?(:)?(\/\/)?/i,'');
return 'http://' + newurl;
}
console.log(prependHTTPtoWebURL(someurl));
console.log(prependHTTPtoWebURL(otherurl));
console.log(prependHTTPtoWebURL(anotherurl));
The ouput in console.log will be:
http://www.google.com
http://google.com
http://google.com
Since you are specifying a subdomain (www) on the first one, that is respected. It avoids ending with four diagonals, like http:////. If your url was something like :google.com, it would also fix it correctly.
You can see it live here: http://jsfiddle.net/zRBUj/
Edit: Adding the /i Kate mentioned.
Change http: to http://
See these links for more info:
Anatomy of a URL
How the web works

Get The Current Domain Name With Javascript (Not the path, etc.)

I plan on buying two domain names for the same site. Depending on which domain is used I plan on providing slightly different data on the page. Is there a way for me to detect the actual domain name that the page is loading from so that I know what to change my content to?
I've looked around for stuff like this but most of it doesn't work the way I want it to.
For instance when using
document.write(document.location)
on JSFiddle it returns
http://fiddle.jshell.net/_display/
i.e. the actual path or whatever that is.
How about:
window.location.hostname
The location object actually has a number of attributes referring to different parts of the URL
Let's suppose you have this url path:
http://localhost:4200/landing?query=1#2
So, you can serve yourself by the location values, as follow:
window.location.hash: "#2"
​
window.location.host: "localhost:4200"
​
window.location.hostname: "localhost"
​
window.location.href: "http://localhost:4200/landing?query=1#2"
​
window.location.origin: "http://localhost:4200"
​
window.location.pathname: "/landing"
​
window.location.port: "4200"
​
window.location.protocol: "http:"
window.location.search: "?query=1"
Now we can conclude you're looking for:
window.location.hostname
If you are not interested in the host name (for example www.beta.example.com) but in the domain name (for example example.com), this works for valid host names:
function getDomainName(hostName)
{
return hostName.substring(hostName.lastIndexOf(".", hostName.lastIndexOf(".") - 1) + 1);
}
function getDomain(url, subdomain) {
subdomain = subdomain || false;
url = url.replace(/(https?:\/\/)?(www.)?/i, '');
if (!subdomain) {
url = url.split('.');
url = url.slice(url.length - 2).join('.');
}
if (url.indexOf('/') !== -1) {
return url.split('/')[0];
}
return url;
}
Examples
getDomain('http://www.example.com'); // example.com
getDomain('www.example.com'); // example.com
getDomain('http://blog.example.com', true); // blog.example.com
getDomain(location.href); // ..
Previous version was getting full domain (including subdomain). Now it determines the right domain depending on preference. So that when a 2nd argument is provided as true it will include the subdomain, otherwise it returns only the 'main domain'
If you wish a full domain origin, you can use this:
document.location.origin
And if you wish to get only the domain, use can you just this:
document.location.hostname
But you have other options, take a look at the properties in:
document.location
You can get it from location object in Javascript easily:
For example URL of this page is:
http://www.stackoverflow.com/questions/11401897/get-the-current-domain-name-with-javascript-not-the-path-etc
Then we can get the exact domain with following properties of location object:
location.host = "www.stackoverflow.com"
location.protocol= "http:"
you can make the full domain with:
location.protocol + "//" + location.host
Which in this example returns http://www.stackoverflow.com
I addition of this we can get full URL and also the path with other properties of location object:
location.href= "http://www.stackoverflow.com/questions/11401897/get-the-current-domain-name-with-javascript-not-the-path-etc"
location.pathname= "questions/11401897/get-the-current-domain-name-with-javascript-not-the-path-etc"
window.location.hostname is a good start. But it includes sub-domains, which you probably want to remove. E.g. if the hostname is www.example.com, you probably want just the example.com bit.
There are, as ever, corner cases that make this fiddly, e.g. bbc.co.uk. The following regex works well for me:
let hostname = window.location.hostname;
// remove any subdomains, e.g. www.example.com -> example.com
let domain = hostname.match(/^(?:.*?\.)?([a-zA-Z0-9\-_]{3,}\.(?:\w{2,8}|\w{2,4}\.\w{2,4}))$/)[1];
console.log("domain: ", domain);
Since this question asks for domain name, not host name, a correct answer should be
window.location.hostname.split('.').slice(-2).join('.')
This works for host names like www.example.com too.
If you are only interested in the domain name and want to ignore the subdomain then you need to parse it out of host and hostname.
The following code does this:
var firstDot = window.location.hostname.indexOf('.');
var tld = ".net";
var isSubdomain = firstDot < window.location.hostname.indexOf(tld);
var domain;
if (isSubdomain) {
domain = window.location.hostname.substring(firstDot == -1 ? 0 : firstDot + 1);
}
else {
domain = window.location.hostname;
}
http://jsfiddle.net/5U366/4/
Use
document.write(document.location.hostname)​
window.location has a bunch of properties. See here for a list of them.
I figure it ought to be as simple as this:
url.split("/")[2]
If you want to get domain name in JavaScript, just use the following code:
var domain_name = document.location.hostname;
alert(domain_name);
If you need to web page URL path so you can access web URL path use this example:
var url = document.URL;
alert(url);
What about this function?
window.location.hostname.match(/\w*\.\w*$/gi)[0]
This will match only the domain name regardless if its a subdomain or a main domain
for my case the best match is window.location.origin
Combining a few answers from the above, the following works really well for me for destroying Cookies:
/**
* Utility method to obtain the domain URI:
*/
fetchDomainURI() {
if (window.location.port.length > 0) {
return window.location.hostname;
}
return `.${window.location.hostname.match(/\w*\.\w*$/gi)[0]}`;
}
Works for IP addresses with ports, e.g., 0.0.0.0:8000 etc, as well as complex domains like app.staging.example.com returning .example.com => allows for cross-domain Cookie setting and destroying.
I'm new to JavaScript, but cant you just use: document.domain ?
Example:
<p id="ourdomain"></p>
<script>
var domainstring = document.domain;
document.getElementById("ourdomain").innerHTML = (domainstring);
</script>
Output:
domain.com
or
www.domain.com
Depending on what you use on your website.
Even if the question is about the domain name, the accepted solution includes the subdomain (eg. you get blog.example.com calling location.hostname).
For future reference I suggest a one-liner to extract only the domain (eg. https://blog.example.com/index.html -> example.com) as Micheal.
location.hostname.split('.').filter(( _, i) => i < 2).join('.')
Beware! It can break when the TLD is composed of two parts (eg. .co.uk). If that's your case change 2 with 3 in the code above.
you can use this to do away with the port number.
var hostname = window.location.host;
var urlWithoutPort = `https://${hostname}`;
console.log(urlWithoutPort);
https://publicsuffix.org/list/
(https://github.com/publicsuffix/list/blob/master/public_suffix_list.dat)
is needed to correctly parse out all domains without suffixes, working with dots as in the answers above will never completely be correct. Feel free to run the above codes samples against the public suffixes dat file to realize this.
You can roll your own code based on this or use a package like https://www.npmjs.com/package/tldts
getDomainWithoutSuffix('google.com'); // returns `google`
getDomainWithoutSuffix('fr.google.com'); // returns `google`
getDomainWithoutSuffix('fr.google.google'); // returns `google`
getDomainWithoutSuffix('foo.google.co.uk'); // returns `google`
getDomainWithoutSuffix('t.co'); // returns `t`
getDomainWithoutSuffix('fr.t.co'); // returns `t`
getDomainWithoutSuffix('https://user:password#example.co.uk:8080/some/path?and&query#hash'); // returns `example`

JavaScript - Get Portion of URL Path

What is the correct way to pull out just the path from a URL using JavaScript?
Example:
I have URL
http://www.somedomain.com/account/search?filter=a#top
but I would just like to get this portion
/account/search
I am using jQuery if there is anything there that can be leveraged.
There is a property of the built-in window.location object that will provide that for the current window.
// If URL is http://www.somedomain.com/account/search?filter=a#top
window.location.pathname // /account/search
// For reference:
window.location.host // www.somedomain.com (includes port if there is one)
window.location.hostname // www.somedomain.com
window.location.hash // #top
window.location.href // http://www.somedomain.com/account/search?filter=a#top
window.location.port // (empty string)
window.location.protocol // http:
window.location.search // ?filter=a
Update, use the same properties for any URL:
It turns out that this schema is being standardized as an interface called URLUtils, and guess what? Both the existing window.location object and anchor elements implement the interface.
So you can use the same properties above for any URL — just create an anchor with the URL and access the properties:
var el = document.createElement('a');
el.href = "http://www.somedomain.com/account/search?filter=a#top";
el.host // www.somedomain.com (includes port if there is one[1])
el.hostname // www.somedomain.com
el.hash // #top
el.href // http://www.somedomain.com/account/search?filter=a#top
el.pathname // /account/search
el.port // (port if there is one[1])
el.protocol // http:
el.search // ?filter=a
[1]: Browser support for the properties that include port is not consistent, See: http://jessepollak.me/chrome-was-wrong-ie-was-right
This works in the latest versions of Chrome and Firefox. I do not have versions of Internet Explorer to test, so please test yourself with the JSFiddle example.
JSFiddle example
There's also a coming URL object that will offer this support for URLs themselves, without the anchor element. Looks like no stable browsers support it at this time, but it is said to be coming in Firefox 26. When you think you might have support for it, try it out here.
window.location.href.split('/');
Will give you an array containing all the URL parts, which you can access like a normal array.
Or an ever more elegant solution suggested by #Dylan, with only the path parts:
window.location.pathname.split('/');
If this is the current url use window.location.pathname otherwise use this regular expression:
var reg = /.+?:\/\/.+?(\/.+?)(?:#|\?|$)/;
var pathname = reg.exec( 'http://www.somedomain.com/account/search?filter=a#top' )[1];
There is a useful Web API method called URL
const url = new URL('https://www.somedomain.com/account/search?filter=a#top');
console.log(url.pathname.split('/').slice(1)); // drop the leading slash
const params = new URLSearchParams(url.search)
console.log("filter:",params.get("filter"))
If you have an abstract URL string (not from the current window.location), you can use this trick:
let yourUrlString = "http://example.com:3000/pathname/?search=test#hash";
let parser = document.createElement('a');
parser.href = yourUrlString;
parser.protocol; // => "http:"
parser.hostname; // => "example.com"
parser.port; // => "3000"
parser.pathname; // => "/pathname/"
parser.search; // => "?search=test"
parser.hash; // => "#hash"
parser.host; // => "example.com:3000"
Thanks to jlong
In case you want to get parts of an URL that you have stored in a variable, I can recommend URL-Parse
const Url = require('url-parse');
const url = new Url('https://github.com/foo/bar');
According to the documentation, it extracts the following parts:
The returned url instance contains the following properties:
protocol: The protocol scheme of the URL (e.g. http:).
slashes: A boolean which indicates whether the protocol is followed by two forward slashes (//).
auth: Authentication information portion (e.g. username:password).
username: Username of basic authentication.
password: Password of basic authentication.
host: Host name with port number.
hostname: Host name without port number.
port: Optional port number.
pathname: URL path.
query: Parsed object containing query string, unless parsing is set to false.
hash: The "fragment" portion of the URL including the pound-sign (#).
href: The full URL.
origin: The origin of the URL.

Getting an absolute URL from a relative one. (IE6 issue)

I'm currently using the following function to 'convert' a relative URL to an absolute one:
function qualifyURL(url) {
var a = document.createElement('a');
a.href = url;
return a.href;
}
This works quite well in most browsers but IE6 insists on returning the relative URL still! It does the same if I use getAttribute('href').
The only way I've been able to get a qualified URL out of IE6 is to create an img element and query it's 'src' attribute - the problem with this is that it generates a server request; something I want to avoid.
So my question is: Is there any way to get a fully qualified URL in IE6 from a relative one (without a server request)?
Before you recommend a quick regex/string fix I assure you it's not that simple. Base elements + double period relative urls + a tonne of other potential variables really make it hell!
There must be a way to do it without having to create a mammoth of a regex'y solution??
How strange! IE does, however, understand it when you use innerHTML instead of DOM methods.
function escapeHTML(s) {
return s.split('&').join('&').split('<').join('<').split('"').join('"');
}
function qualifyURL(url) {
var el= document.createElement('div');
el.innerHTML= 'x';
return el.firstChild.href;
}
A bit ugly, but more concise than Doing It Yourself.
As long as the browser implements the <base> tag correctly, which browsers tend to:
function resolve(url, base_url) {
var doc = document
, old_base = doc.getElementsByTagName('base')[0]
, old_href = old_base && old_base.href
, doc_head = doc.head || doc.getElementsByTagName('head')[0]
, our_base = old_base || doc_head.appendChild(doc.createElement('base'))
, resolver = doc.createElement('a')
, resolved_url
;
our_base.href = base_url || '';
resolver.href = url;
resolved_url = resolver.href; // browser magic at work here
if (old_base) old_base.href = old_href;
else doc_head.removeChild(our_base);
return resolved_url;
}
Here's a jsfiddle where you can experiment with it: http://jsfiddle.net/ecmanaut/RHdnZ/
You can make it work on IE6 just cloning the element:
function qualifyURL(url) {
var a = document.createElement('a');
a.href = url;
return a.cloneNode(false).href;
}
(Tested using IETester on IE6 and IE5.5 modes)
I found on this blog another method that really looks like #bobince solution.
function canonicalize(url) {
var div = document.createElement('div');
div.innerHTML = "<a></a>";
div.firstChild.href = url; // Ensures that the href is properly escaped
div.innerHTML = div.innerHTML; // Run the current innerHTML back through the parser
return div.firstChild.href;
}
I found it a little more elegant, not a big deal.
URI.js seems to solve the issue:
URI("../foobar.html").absoluteTo("http://example.org/hello/world.html").toString()
See also http://medialize.github.io/URI.js/docs.html#absoluteto
Not testeed with IE6, but maybe helpful for others searching to the general issue.
I actually wanted an approach to this that didn't require modifying the original document (not even temporarily) but still used the browser's builtin url parsing and such. Also, I wanted to be able to provide my own base (like ecmanaught's answer). It's rather straightforward, but uses createHTMLDocument (could be replaced with createDocument to be a bit more compatible possibly):
function absolutize(base, url) {
d = document.implementation.createHTMLDocument();
b = d.createElement('base');
d.head.appendChild(b);
a = d.createElement('a');
d.body.appendChild(a);
b.href = base;
a.href = url;
return a.href;
}
http://jsfiddle.net/5u6j403k/
This solution works in all browsers.
/**
* Given a filename for a static resource, returns the resource's absolute
* URL. Supports file paths with or without origin/protocol.
*/
function toAbsoluteURL (url) {
// Handle absolute URLs (with protocol-relative prefix)
// Example: //domain.com/file.png
if (url.search(/^\/\//) != -1) {
return window.location.protocol + url
}
// Handle absolute URLs (with explicit origin)
// Example: http://domain.com/file.png
if (url.search(/:\/\//) != -1) {
return url
}
// Handle absolute URLs (without explicit origin)
// Example: /file.png
if (url.search(/^\//) != -1) {
return window.location.origin + url
}
// Handle relative URLs
// Example: file.png
var base = window.location.href.match(/(.*\/)/)[0]
return base + url
However, it doesn't support relative URLs with ".." in them, like "../file.png".
This is the function I use to resolve basic relative URLs:
function resolveRelative(path, base) {
// Absolute URL
if (path.match(/^[a-z]*:\/\//)) {
return path;
}
// Protocol relative URL
if (path.indexOf("//") === 0) {
return base.replace(/\/\/.*/, path)
}
// Upper directory
if (path.indexOf("../") === 0) {
return resolveRelative(path.slice(3), base.replace(/\/[^\/]*$/, ''));
}
// Relative to the root
if (path.indexOf('/') === 0) {
var match = base.match(/(\w*:\/\/)?[^\/]*\//) || [base];
return match[0] + path.slice(1);
}
//relative to the current directory
return base.replace(/\/[^\/]*$/, "") + '/' + path.replace(/^\.\//, '');
}
Test it on jsfiddle: https://jsfiddle.net/n11rg255/
It works both in the browser and in node.js or other environments.
I found this blog post that suggests using an image element instead of an anchor:
http://james.padolsey.com/javascript/getting-a-fully-qualified-url/
That works to reliably expand a URL, even in IE6. But the problem is that the browsers that I have tested will immediately download the resource upon setting the image src attribute - even if you set the src to null on the next line.
I am going to give bobince's solution a go instead.
If url does not begin with '/'
Take the current page's url, chop off everything past the last '/'; then append the relative url.
Else if url begins with '/'
Take the current page's url and chop off everything to the right of the single '/'; then append the url.
Else if url starts with # or ?
Take the current page's url and simply append url
Hope it works for you
If it runs in the browser, this sort of works for me..
function resolveURL(url, base){
if(/^https?:/.test(url))return url; // url is absolute
// let's try a simple hack..
var basea=document.createElement('a'), urla=document.createElement('a');
basea.href=base, urla.href=url;
urla.protocol=basea.protocol;// "inherit" the base's protocol and hostname
if(!/^\/\//.test(url))urla.hostname=basea.hostname; //..hostname only if url is not protocol-relative though
if( /^\//.test(url) )return urla.href; // url starts with /, we're done
var urlparts=url.split(/\//); // create arrays for the url and base directory paths
var baseparts=basea.pathname.split(/\//);
if( ! /\/$/.test(base) )baseparts.pop(); // if base has a file name after last /, pop it off
while( urlparts[0]=='..' ){baseparts.pop();urlparts.shift();} // remove .. parts from url and corresponding directory levels from base
urla.pathname=baseparts.join('/')+'/'+urlparts.join('/');
return urla.href;
}

Categories