how to check port number in url string? - javascript

Can I check whether the port number is existing in a given URL string or not?
Like sometimes a user can type 202.567.89.254:8088 or http://202.567.89.254:8088/ or http://202.567.89.254.
Out of all the above options, if the port number is existing, then do nothing otherwise append 8080 by default with an end slash 8080/.
Is it possible in JavaScript?

You can try to use the location object and use:
location.port
The HTMLHyperlinkElementUtils.port property is a USVString containing
the port number of the URL.

Here you go the easiest way, set the href attribute.
var parser = document.createElement('a');
parser.href = "http://example.com:3000/pathname/?search=test#hash";
console.log(parser.protocol); // => "http:"
console.log(parser.hostname); // => "example.com"
console.log(parser.port); // => "3000"
console.log(parser.pathname); // => "/pathname/"
console.log(parser.host); // => "example.com:3000"
read more here

You can use location.port property.
if(location.port){//then there is port}
else{//No port}

Try below code
urlSplit = url.split(":")
if(urlSplit.length==3){
port = urlSplit[2];
}
else{
port = 80;
}

You can check Location
Location.port will serve your purpose

See if this works for you:
function appendPort(url){
if(!url.match(/\:\d+$/)){
return url + ":8080";
}
}
If you want to do that on user entered location:
if(!location.port){
location.port = 8080; // doing this will take care of rest of the URL component
}
:)

use location.port. Sample example below.
function appendPort(){
if(location.port.length === 0){
location.host = location.host + ":8080/";
}
}

Use this:
if(location.port){
//then there is port
//you may alert() if you want
}
else{
location.port=8080;
}

You can use Location Object of js
location.port

Just use location in debugger you will get host hostname href origin pathname port protocol and many more values

Related

What is the best way to determine if a URL belongs to the current domain in JavaScript?

I have a URL. It might be relative (e.g. not start with https://, etc.), or it might not be (starts with https://, etc.).
How can I determine if this URL refers to the same domain as window.location?
(I'm creating a XMLHttpRequest and adding a cookie to it. Can only add the cookie if the URL I'm requesting is the same as the one I'm at. It's a secret cookie.)
The simplest way is actually to leverage the DOM: when you insert a URL into an <a> tag, the browser will actually resolve the URL immediately—i.e. when you retrieve the element's href attribute using JS, it will return an absolute path.
Then, you can simply check if the resolved path contains window.location.origin:
function doesUrlBelongsToCurrentDomain(url) {
const link = document.createElement('a');
link.href = url;
return link.href.includes(window.location.origin);
}
console.log(doesUrlBelongsToCurrentDomain('https://google.com')); // false
console.log(doesUrlBelongsToCurrentDomain('./relative-link')); // true
console.log(doesUrlBelongsToCurrentDomain('/relative-link')); // true
For a ES5-compliant version, swap String.prototype.includes with String.prototype.indexOf:
return link.href.indexOf(window.location.origin) !== -1;
Also, if your browser does not support window.location.origin, you will need to construct it manually:
var origin = window.location.protocol + '//' + window.location.hostname + (window.location.port ? ':' + window.location.port : '');
...therefore, the IE11-compatible version (if IE11 support is absolutely needed), will be as follow:
function doesUrlBelongsToCurrentDomain(url) {
var link = document.createElement('a');
link.href = url;
var origin = window.location.protocol + '//' + window.location.hostname + (window.location.port ? ':' + window.location.port : '');
return link.href.indexOf(origin) !== -1;
}
You can create an URL object from the url to test, and compare it to the current location origin:
const sameOrigin = new URL('URL_TO_TEST').origin === window.location.origin;

How to split url to get url path in JavaScript

I have constructed a url path that are pointing to different hostname www.mysite.com, so for example:
var myMainSite = 'www.mymainsite.com' + '/somepath';
so this is equivalent to www.mymainsite.com/path/path/needthispath/somepath.
How I'm doing it now is like the code below and this gives me a bunch of indexes of the url in the console.log.
var splitUrl = myMainSite.split('/');
console.log looks like:
0: http://
1: www.
2: mysite.com
3: path
4: path
5: needthispath
6: somepath
and I concat them like splitUrl[5]+'/'+splitUrl[6] and it doesn't look pretty at all.
So my question is how to split/remove url location http://www.mymainsite.com/ to get the url path needthispath/somepath in js? Is there a quicker and cleaner way of doing this?
First solution (URL object)
The URL object can be used for parsing, constructing, normalizing, encoding URLs, and so on.
var url = 'http://www.mymainsite.com/somepath/path2/path3/path4';
var pathname = new URL(url).pathname;
console.log(pathname);
The URL interface represents an object providing static methods used
for creating object URLs.
See the documentation for URL interface on Mozilla MDN
The Browser support is pretty good in 2017 (~ 90% but not IE11 nor below)
Second solution (a kind of a hack)
var urlHack = document.createElement('a');
urlHack.href = 'http://www.mymainsite.com/somepath/path2/path3/path4';
console.log(urlHack.pathname);
// you can even call this object with these properties:
// protocol, host, hostname, port, pathname, hash, search, origin
Why don't you use the split function and work from there.
The split function will break your URL out fully and from there you just need to look for the second last and last items.
Here is an example:
var initial_url = 'http://www.mymainsite.com/path/path/needthispath/somepath';
var url = initial_url .split( '/' );
var updated_url= document.location.hostname + '/' + url[ url.length - 2 ] + '/' + url[ url.length - 1 ];
You can use the URL API, though support is variable.
Alternatively, you could use URI.js.
Both allow you to get different parts of an URL, as well as build new URLs from parts.
function url($url) {
var url = $url.split( '//' );
if (url[0] === "http:" || url[0] === "https:") {
var protocol = url[0] + "//";
var host = url[1].split( '/' )[0];
url = protocol + host;
var path = $url.split(url)[1];
return {
protocol: protocol,
host: host,
path: path
};
}
}
var $url = url("http://www.mymainsite.com/path/path/needthispath/somepath");
console.log($url.protocol); // http://
console.log($url.host); // www.mymainsite.com
console.log($url.path); // /path/path/needthispath/somepath

How to get base url with jquery or javascript?

In joomla php there I can use $this->baseurl to get the base path, but I wanted to get the base path in jquery.
The base path may be any of the following example:
http://www.example.com/
http://localhost/example
http://www.example.com/sub/example
The example may also change.
I think this will work well for you:
var base_url = window.location.origin;
var host = window.location.host;
var pathArray = window.location.pathname.split( '/' );
This one will help you...
var getUrl = window.location;
var baseUrl = getUrl .protocol + "//" + getUrl.host + "/" + getUrl.pathname.split('/')[1];
This will get base url
var baseurl = window.location.origin+window.location.pathname;
document.baseURI returns base URL also respecting the value in <base/> tag
https://developer.mozilla.org/en-US/docs/Web/API/Node/baseURI
This is an extremely old question, but here are the approaches I personally use ...
Get Standard/Base URL
As many have already stated, this works for most situations.
var url = window.location.origin;
Get Absolute Base URL
However, this simple approach can be used to strip off any port numbers.
var url = "http://" + location.host.split(":")[0];
Edit: To address the concern, posed by Jason Rice, the following can be used to automatically insert the correct protocol type ...
var url = window.location.protocol + "//" + location.host.split(":")[0];
Set Base URL
As a bonus -- the base URL can then be redefined globally.
document.head.innerHTML = document.head.innerHTML + "<base href='" + url + "' />";
the easiest way to get base url in JavaScript
window.location.origin
This is not possible from javascript, because this is a server-side property. Javascript on the client cannot know where joomla is installed. The best option is to somehow include the value of $this->baseurl into the page javascript and then use this value (phpBaseUrl).
You can then build the url like this:
var loc = window.location;
var baseUrl = loc.protocol + "//" + loc.hostname + (loc.port? ":"+loc.port : "") + "/" + phpBaseUrl;
var getUrl = window.location;
var baseurl = getUrl.origin; //or
var baseurl = getUrl.origin + '/' +getUrl.pathname.split('/')[1];
But you can't say that the baseurl() of CodeIgniter(or php joomla) will return the same value, as it is possible to change the baseurl in the .htaccess file of these frameworks.
For example :
If you have an .htaccess file like this in your localhost :
RewriteEngine on
RewriteBase /CodeIgniter/
RewriteCond $1 !^(index.php|resources|robots.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]
The $this->baseurl() will return http://localhost/CodeIgniter/
Had the same issue a while ago, my problem was, I simply needed the base url. There are a lot of detailed options here but to get around this, simply use the window.location object. Actually type this in the browser console and hit enter to select your options there. Well for my case it was simply:
window.location.origin
I've run into this need on several Joomla project. The simplest way I've found to address is to add a hidden input field to my template:
<input type="hidden" id="baseurl" name="baseurl" value="<?php echo $this->baseurl; ?>" />
When I need the value in JavaScript:
var baseurl = document.getElementById('baseurl').value;
Not as fancy as using pure JavaScript but simple and gets the job done.
You can easily get it with:
var currentUrl = window.location.href;
or, if you want the original URL, use:
var originalUrl = window.location.origin;
The format is hostname/pathname/search
So the url is :
var url = window.location.hostname + window.location.pathname + window.location.hash
For your case
window.location.hostname = "stackoverflow.com"
window.location.pathname ="/questions/25203124/how-to-get-base-url-with-jquery-or-javascript"
window.location.hash = ""
So basically the baseurl = hostname = window.location.hostname
I am surprised that non of the answers consider the base url if it was set in <base> tag. All current answers try to get the host name or server name or first part of address. This is the complete logic which also considers the <base> tag (which may refer to another domain or protocol):
function getBaseURL(){
var elem=document.getElementsByTagName("base")[0];
if (typeof(elem) != 'undefined' && elem != null){
return elem.href;
}
return window.location.origin;
}
Jquery format:
function getBaseURL(){
if ($("base").length){
return $("base").attr("href");
}
return window.location.origin;
}
Without getting involved with the logic above, the shorthand solution which considers both <base> tag and window.location.origin:
Js:
var a=document.createElement("a");
a.href=".";
var baseURL= a.href;
Jquery:
var baseURL= $('<a href=".">')[0].href
Final note: for a local file in your computer (not on a host) the window.location.origin only returns the file:// but the sorthand solution above returns the complete correct path.
Here's a short one:
const base = new URL('/', location.href).href;
console.log(base);
I would recommend for everyone to create HTML base tag in development, then assign the href dynamically, so in production whatever host a client uses, it will automacically addapt to it:
<html>
<title>Some page title</titile>
<script type="text/javascript">
var head = document.getElementsByTagName('head')[0];
var base = document.createElement("base");
base.href = window.document.location.origin;
head.appendChild(base);
</script>
</head>
...
So if you are in localhot:8080, you will reach every linked or referenced file from the base, eg: http://localhost:8080/some/path/file.html
If you are in www.example.com, it will be http://www.example.com/some/path/file.html
Also note that, every location you're on, you should not use references like globs in hrefs, eg: Parent location causes http://localhost:8080/ not http://localhost:8080/some/path/.
Pretent you reference all hyperlinks as full sentenced without the bas url.
window.location.origin+"/"+window.location.pathname.split('/')[1]+"/"+page+"/"+page+"_list.jsp"
almost same as Jenish answer but a little shorter.
I was just on the same stage and this solution works for me
In the view
<?php
$document = JFactory::getDocument();
$document->addScriptDeclaration('var base = \''.JURI::base().'\'');
$document->addScript('components/com_name/js/filter.js');
?>
In js file you access base as a variable for example in your scenario:
console.log(base) // will print
// http://www.example.com/
// http://localhost/example
// http://www.example.com/sub/example
I do not remember where I take this information to give credit, if I find it I will edit the answer
A simpler answer is here, window.location.href = window.location.origin;
Easy
$('<img src=>')[0].src
Generates a img with empty src-name forces the browser to calculate the base-url by itself, no matter if you have /index.html or anything else.
var getUrl = window.location;
var baseUrl = getUrl .protocol + "//" + getUrl.host + "/" + getUrl.pathname.split('/')[1];
Here's something quick that also works with file:// URLs.
I came up with this one-liner:
[((1!=location.href.split(location.href.split("/").pop())[0].length?location.href.split(location.href.split("/").pop())[0]:(location.protocol,location.protocol+"//" + location.host+"/"))).replace(location.protocol+"//"+location.protocol+"//"+location.protocol+"://")]
You mentioned that the example.com may change so I suspect that actually you need the base url just to be able to use relative path notation for your scripts. In this particular case there is no need to use scripting - instead add the base tag to your header:
<head>
<base href="http://www.example.com/">
</head>
I usually generate the link via PHP.
In case anyone would like to see this broken out into a very robust function
function getBaseURL() {
var loc = window.location;
var baseURL = loc.protocol + "//" + loc.hostname;
if (typeof loc.port !== "undefined" && loc.port !== "") baseURL += ":" + loc.port;
// strip leading /
var pathname = loc.pathname;
if (pathname.length > 0 && pathname.substr(0,1) === "/") pathname = pathname.substr(1, pathname.length - 1);
var pathParts = pathname.split("/");
if (pathParts.length > 0) {
for (var i = 0; i < pathParts.length; i++) {
if (pathParts[i] !== "") baseURL += "/" + pathParts[i];
}
}
return baseURL;
}
Split and join the URL:
const s = 'http://free-proxy.cz/en/abc'
console.log(s.split('/').slice(0,3).join('/'))
Getting the base url
|Calls controller from js
function getURL() {
var windowurl = window.location.href;
var baseUrl = windowurl.split('://')[1].split('/')[0]; //split function
var xhr = new XMLHttpRequest();
var url='http://'+baseUrl+'/url from controller';
xhr.open("GET", url);
xhr.send(); //object use to send
xhr.onreadystatechange=function() {
if(xhr.readyState==4 && this.status==200){
//console.log(xhr.responseText); //the response of the request
document.getElementById("id from where you called the function").innerHTML = xhr.responseText;
}
}
}
Put this in your header, so it will be available whenever you need it.
var base_url = "<?php echo base_url();?>";
You will get http://localhost:81/your-path-file or http://localhost/your-path-file.

Check if a string starts with http using Javascript

I've been searching all over for an answer to this and all of the answers I've found haven't been in JavaScript.
I need a way, in javascript, to check if a string starts with http, https, or ftp. If it doesn't start with one of those I need to prepend the string with http://. indexOf won't work for me I don't think as I need either http, https or ftp. Also I don't want something like google.com/?q=http://google.com to trigger that as being valid as it doesn't start with an http whereas indexOf would trigger that as being true (if I'm not entirely mistaken).
The closest PHP regex I've found is this:
function addhttp($url) {
if (!preg_match("~^(?:f|ht)tps?://~i", $url)) {
$url = "http://" . $url;
}
return $url;
}
Source: How to add http if its not exists in the url
I just don't know how to convert that to javascript. Any help would be greatly appreciated.
export const getValidUrl = (url = "") => {
let newUrl = window.decodeURIComponent(url);
newUrl = newUrl.trim().replace(/\s/g, "");
if(/^(:\/\/)/.test(newUrl)){
return `http${newUrl}`;
}
if(!/^(f|ht)tps?:\/\//i.test(newUrl)){
return `http://${newUrl}`;
}
return newUrl;
};
Tests:
expect(getValidUrl('https://www.test.com')).toBe('https://www.test.com');
expect(getValidUrl('http://www.test.com')).toBe('http://www.test.com');
expect(getValidUrl(' http : / / www.test.com')).toBe('http://www.test.com');
expect(getValidUrl('ftp://www.test.com')).toBe('ftp://www.test.com');
expect(getValidUrl('www.test.com')).toBe('http://www.test.com');
expect(getValidUrl('://www.test.com')).toBe('http://www.test.com');
expect(getValidUrl('http%3A%2F%2Fwww.test.com')).toBe('http://www.test.com');
expect(getValidUrl('www . test.com')).toBe('http://www.test.com');
This should work:
var pattern = /^((http|https|ftp):\/\/)/;
if(!pattern.test(url)) {
url = "http://" + url;
}
jsFiddle
var url = "http://something.com"
if( url.indexOf("http") == 0 ) {
alert("yeah!");
} else {
alert("No no no!");
}
Non-Regex declarative way:
const hasValidUrlProtocol = (url = '') =>
['http://', 'https://', 'ftp://'].some(protocol => url.startsWith(protocol))
This should work:
var re = /^(http|https|ftp)/
Refining previous answers a bit more, I used new RegExp(...) to avoid messy escapes, and also added an optional s.
var pattern = new RegExp('^(https?|ftp)://');
if(!pattern.test(url)) {
url = "http://" + url;
}
var pattern = new RegExp('^(https?|ftp)://');
console.log(pattern.test('http://foo'));
console.log(pattern.test('https://foo'));
console.log(pattern.test('ftp://foo'));
console.log(pattern.test('bar'));
Best readability I'd say is to use .startsWith('theString').
The code below checks for both http://, https:// and ftp:// and sets okUrl to a boolean true if any of them comply, by using the || which means or.
When you know if the url contains none of those strings, then just just add http:// to the start of the string either with literals (${})
let url = 'google.com'
const urlOK = url.startsWith('http://') || url.startsWith('https://') || url.startsWith('ftp://')
if (!urlOk) url = `http://${url}`
// => 'http://google.com'
or with simple string concat, which can be done in various ways, for example:
url = 'http://' + url
Read more about it, and test it, here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith

How to extract the hostname portion of a URL in JavaScript

Is there a really easy way to start from a full URL:
document.location.href = "http://aaa.bbb.ccc.com/asdf/asdf/sadf.aspx?blah"
And extract just the host part:
aaa.bbb.ccc.com
There's gotta be a JavaScript function that does this reliably, but I can't find it.
Suppose that you have a page with this address: http://sub.domain.com/virtualPath/page.htm.
Use the following in page code to achieve those results:
Property
Result
window.location.host
sub.domain.com:8080 or sub.domain.com:80
window.location.hostname
sub.domain.com
window.location.protocol
http:
window.location.port
8080 or 80
window.location.pathname
/virtualPath
window.location.origin
http://sub.domain.com (Might include :port too*****)
Update: about the .origin
***** As the ref states, browser compatibility for window.location.origin is not clear. I've checked it in chrome and it returned http://sub.domain.com:port if the port is anything but 80, and http://sub.domain.com if the port is 80.
Special thanks to #torazaburo for mentioning that to me.
You could concatenate the location protocol and the host:
var root = location.protocol + '//' + location.host;
For a url, let say 'http://stackoverflow.com/questions', it will return 'http://stackoverflow.com'
The accepted answer didn't work for me since wanted to be able to work with any arbitary url's, not just the current page URL.
Take a look at the URL object:
var url = new URL("http://aaa.bbb.ccc.com/asdf/asdf/sadf.aspx?blah");
url.protocol; // "http:"
url.hostname; // "aaa.bbb.ccc.com"
url.pathname; // "/asdf/asdf/sadf.aspx"
url.search; // "?blah"
Use document.location object and its host or hostname properties.
alert(document.location.hostname); // alerts "stackoverflow.com"
There are two ways. The first is a variant of another answer here, but this one accounts for non-default ports:
function getRootUrl() {
var defaultPorts = {"http:":80,"https:":443};
return window.location.protocol + "//" + window.location.hostname
+ (((window.location.port)
&& (window.location.port != defaultPorts[window.location.protocol]))
? (":"+window.location.port) : "");
}
But I prefer this simpler method (which works with any URI string):
function getRootUrl(url) {
return url.toString().replace(/^(.*\/\/[^\/?#]*).*$/,"$1");
}
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
Try
document.location.host
or
document.location.hostname
use
window.location.origin
and for: "http://aaa.bbb.ccc.ddd.com/sadf.aspx?blah"
you will get: http://aaa.bbb.ccc.ddd.com/
There is another hack I use and never saw in any StackOverflow response :
using "src" attribute of an image will yield the complete base path of your site.
For instance :
var dummy = new Image;
dummy.src = '$'; // using '' will fail on some browsers
var root = dummy.src.slice(0,-1); // remove trailing '$'
On an URL like http://domain.com/somesite/index.html,
root will be set to http://domain.com/somesite/.
This also works for localhost or any valid base URL.
Note that this will cause a failed HTTP request on the $ dummy image.
You can use an existing image instead to avoid this, with only slight code changes.
Another variant uses a dummy link, with no side effect on HTTP requests :
var dummy = document.createElement ('a');
dummy.href = '';
var root = dummy.href;
I did not test it on every browser, though.
Check this:
alert(window.location.hostname);
this will return host name as www.domain.com
and:
window.location.host
will return domain name with port like www.example.com:80
For complete reference check Mozilla developer site.
I know this is a bit late, but I made a clean little function with a little ES6 syntax
function getHost(href){
return Object.assign(document.createElement('a'), { href }).host;
}
It could also be writen in ES5 like
function getHost(href){
return Object.assign(document.createElement('a'), { href: href }).host;
}
Of course IE doesn't support Object.assign, but in my line of work, that doesn't matter.
I would like to specify something. If someone want to get the whole url with path like I need, can use:
var fullUrl = window.location.protocol + "//" + window.location.hostname + window.location.pathname;
Regex provides much more flexibility.
//document.location.href = "http://aaa.bbb.ccc.com/asdf/asdf/sadf.aspx?blah
//1.
var r = new RegExp(/http:\/\/[^/]+/);
var match = r.exec(document.location.href) //gives http://aaa.bbb.ccc.com
//2.
var r = new RegExp(/http:\/\/[^/]+\/[^/]+/);
var match = r.exec(document.location.href) //gives http://aaa.bbb.ccc.com/asdf
My solution works in all web browsers including Microsoft Internet Explorer and doesn't use any regular expression, it's inspired of Noah Cardoza and Martin Konecny solutions:
function getHostname(href) {
if (typeof URL === 'object') {
// workaround for MS IE 11 (Noah Cardoza's solution but without using Object.assign())
var dummyNode = document.createElement('a');
dummyNode.href = href;
return dummyNode.hostname;
} else {
// Martin Konecny's solution
return new URL(href).hostname;
}
}
You can split the URL string using /
const exampleURL = "Https://exampleurl.com/page1/etc/etc"
const URLsplit = exampleURL.split("/")
console.log(URLsplit)
console.log(URLsplit[2])
Result. exampleurl.com

Categories

Resources