i have url like this :
http://192.168.6.1/Images/Work3ererg.png
http://192.168.6.1/Images/WorwefewfewfefewfwekThumb.png
http://192.168.6.1/Images/ewfefewfewfewf23243.png
http://192.168.6.1/Images/freferfer455ggg.png
http://192.168.6.1/Images/regrgrger54654654.png
i would like to know http://192.168.6.1 from those url...how can i achieve this using jquery or javascript?
what am i trying to do it :
i got this string from my JavaScript : http://192.168.6.1/Images/Work3ererg.png
using this javscript string :
i want to put **https://192.168.6.1/** instead of **http://localhost:37774** including http
$("#" + id).css("background", "rgba(0, 0, 0, 0) url(http://localhost:37774/Images/PBexVerticalLine1.png) no-repeat scroll 0% 0% / auto padding-box border-box")
Thanks
var url = 'http://192.168.6.1/Images/Work3ererg.png';
var host = url.substr(0,url.indexOf('/',7));
url.indexOf('/',7)means search / after http://
Then use substr to get string from start to the first / after http://
you can use RegularExpression (pure JavaScript) to do this job
for example you can use
var ip = ''; // will contain the ip address
var ips = [] // ips is an array that will contain all the ip address
var url = 'http://192.168.6.1/Images/Work3ererg.png';
url.replace(/http:\/\/(.+?)\//,function(all,first){
// first will be something like 192.168.6.1
// while all will be something like http://192.168.6.1
ip = first;
});
// url can be a a list of ip address in this case we should add the
// g flag(which means global, not just the first match but all the matches )
url ='http://192.168.6.1/Images/Work3ererg.png';
url +='http://192.168.6.2/Images/Work3ererg.png';
url.replace(/http:\/\/(.+?)\//g,function(all,first){
ips.push(first);
});
If browser support (IE 10 and higher and recent browser), you could use the URL object.
You simply have to do that :
var test = new URL('http://192.168.6.1/Images/regrgrger54654654.png')
console.log(test.origin)
If you want to use a regular expression, that would do it for this case :
var url = 'http://192.168.6.1/Images/regrgrger54654654.png'
console.log(url.match(/https?:\/{2}[^\/]*/)[0]);
http://jsfiddle.net/8cd67Lzs/
Extending the answer from:
https://stackoverflow.com/a/736970/1026017
var getHostname = function(href) {
var l = document.createElement("a");
l.href = href;
return l.hostname;
};
Just replace part of string with another string:
var originalString = "http://192.168.6.1/Images/freferfer455ggg.png";
var newString = originalString.replace("http://192.168.6.1/","https://192.168.6.1/");
console.log(newString);
Related
My intention
pull out language code from my two type of URL strings
My question
How do I make a split between two different URL structures? I have two URL strucutres, listed as examples below under the code.
My problem
I can't figure out how I should split the two different variables separately or together in one line with cc =... using custom javascript with Google Tag Manager
Code
function() {
cc = {{Page Path}}.split("/")[1].toLowerCase();
cc = {{virtualURL}}.split("/#/")[1].toLowerCase();
if(cc.length == 2) {
cc = cc;
} else {
cc = 'other';
}
return cc;
}
Example of {{Page Path}} - https://www.example.com/en/.....
Example of {{virtualURL}} - https://www.booking.example.com/#/en/........
Note
In both examples I want to be able to pull out en successfully.
Any solution here is likely to be fragile, you could have https://example.com/xy/ where xy isn't meant to be a language code.
But allowing for that, and allowing only two-character language codes:
var rexGetLang = /\/([a-z]{2})\//;
function getLang(url) {
var match = rexGetLang.exec(url);
return match ? match[1] : "other";
}
console.log(getLang("https://www.example.com/en/....."));
console.log(getLang("https://www.booking.example.com/#/en/........"));
Or if you want to allow for en-GB and such:
var rexGetLang = /\/([a-z]{2}(?:-[A-Z]{2})?)\//;
function getLang(url) {
var match = rexGetLang.exec(url);
return match ? match[1] : "other";
}
console.log(getLang("https://www.example.com/en/....."));
console.log(getLang("https://www.booking.example.com/#/en/........"));
console.log(getLang("https://www.booking.example.com/........"));
console.log(getLang("https://www.example.com/en-GB/....."));
console.log(getLang("https://www.booking.example.com/#/en-US/........"));
We can take out the language code simply by splitting the URL by /. Let's see what we get when we split the two URL's given as the example:
https://www.example.com/en/ - ["https:", "", "www.example.com", "en", ""]
https://www.booking.example.com/#/en/ - ["https:", "", "www.booking.example.com", "#", "en", ""]
In the above examples we can see that language code is either coming at 3rd index (1st example) or at the 4th index (2nd example) which can be taken care by an if condition. Let's see how:
let url = 'https://www.booking.example.com/#/en/';
let urlTokens = url.split('/');
let languageCode = urlTokens[3] === '#' ? urlTokens[4] : urlTokens[3];
console.log(languageCode);
// Web API for handling URL https://developer.mozilla.org/en-US/docs/Web/API/URL
const url = new URL('https://www.example.com/en/website');
url.hostname; // 'example.com'
url.port; // ''
url.search; // ''
url.pathname; // '/en/website'
url.protocol; // 'https:'
// RegEx to see if /en/ exists https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
new RegExp(/\/en\//).test(url.pathname) // true
function getLanguage(url) {
var rgx = /^https:\/\/[^\/]+\/(?:#\/)?([a-z]+)/;
var language = url.match(rgx)[1];
return language;
}
var url = 'https://www.booking.example.com/#/en/';
var language = getLanguage(url);
Here's the situation:
function STP() { var LOC = window.location.href;
var CSV = LOC.substring(LOC.indexOf(',')+1);
var ARR = CSV.split(',');
var STR = ARR[ARR.length -1 ];
var POS = window.document.getElementById(STR).offsetTop;
alert( STR ); };
Explained:
When the page loads, the onload calls the script.
The script gets the location.href and Extracts the element ID by
creating an array and referencing the last one.
So far so good.
I then use that to reference an element ID to get its position.
But it doesn't work.
The STR alert indicates the proper value when it's placed above POS, not below. The script doesn't work at all below that point when the STR var reference is used.
However if I do a direct reference to the ID ('A01') no problem.
Why does one work and not the other when both values are identical? I've tried other ways like using a hash instead of a comma and can extract the value that with .location.hash, but it doesn't work either.
The problem is that when you do
LOC.substring(LOC.indexOf(',') + 1);
you're putting everything after the , into the CSV variable. But there is a space between the comma and the 'A01'. So, the interpreter reduces it to:
var POS = window.document.getElementById(' A01').offsetTop;
But your ID is 'A01', not ' A01', so the selector fails.
function STP() {
var LOC = 'file:///M:/Transfers/Main%20Desktop/Export/USI/2018/Catalog/CAT-Compilations-01a.htm?1525149288810, A01';
var CSV = LOC.substring(LOC.indexOf(',') + 1);
var ARR = CSV.split(',');
var STR = ARR[ARR.length - 1];
console.log(`'${STR}'`);
}
STP();
To solve this, you can increase the index by one:
LOC.substring(LOC.indexOf(',') + 2);
But it would probably be better not to put spaces in URLs when not necessary - if possible, send the user to 'file:///M:/Transfers/Main%20Desktop/Export/USI/2018/Catalog/CAT-Compilations-01a.htm?1525149288810,A01' instead.
var url = window.location.href.toString();
the above line gives me the url of my current page correctly and my url is:
http://localhost/xyzCart/products.php?cat_id=35
However, using javascript how can i get only a portion of the url i.e. from the above url i just want
products.php?cat_id=35
How to accomplish this plz help.I have looked at similar questions in this forum but none were any help for me..
You can sliply use this:
var url = window.location.href.toString();
var newString = url.substr(url.lastIndexOf(".") + 1));
This will result in: php?cat_id=35
Good luck /Zorken17
You can use the location of the final /:
var page = url.substr(url.substr(0, (url + "?").indexOf("?")).lastIndexOf("/") + 1);
(This allows for / in a query string)
You can get your desired result by using javascript split() method.check this link for further detail
https://jsfiddle.net/x06ywtvo/
var urls = [
"http://localhost/xyzCart/products.php?cat_id=35",
"http://localhost/xyzCart/products.php",
"http://www.google.com/xyzCart/products.php?cat_id=37"
];
var target = $('#target');
for(var i=0;i<urls.length;i++){
var index = urls[i].indexOf("xyzCart");
var sub = urls[i].substring(index, urls[i].length);
target.append("<div>" + sub + "</div>");
}
Try the folowing javacript code to get the part you need. It splits up your url by the "/"s and takes the fourth part. This is superior to substr solutions in terms of descriptive clarity.
url.split("/")[4]
Or if url can contain more "/" path parts, then simply take the last split part.
var parts = url.split("/");
console.log( parts[parts.length-1] );
You will get all necessary values in window.location object.
Kindly check on following CodePen Link for proper output.
I have added parameter test=1
Link: http://codepen.io/rajesh_dixit/pen/EVebJe?test=1
Code
(function() {
var url = window.location.pathname.split('/');
var index = 1;
document.write("URL: ");
document.write(window.location.href);
document.write("<br/> Full Path: ");
document.write(window.location.pathname);
document.write("<br/> Last Value:")
// For cases where '/' comes at the end
if(!url[url.length - index])
index++;
document.write(url[url.length-index])
document.write("<br/> Query Parameter: ");
document.write(window.location.search.substring(1));
})()
I have tried googling this but can't find what I'm looking for. I have a url that has a number in it. I want to be able to take the number that is there and depending on what number is there then interject a name back into the url. For example:
Let's say the url is: www.example.com/video15637
Can I take that number and then do something like:
var nameVariable;
if(video15637){
nameVariable = video15637;
}
if(video26597){
nameVariable = video26597;
}
if(video18737){
nameVariable = video18737;
}
then, somehow interject the namevariable back into the url that is displayed?
You can try with:
var a = document.createElement('a');
a.href = 'http://www.example.com/video15637';
var nameVariable = a.pathname.substr(1); // video15637
You can simple use .split() or combination of .substr() and .lastIndexOf()
var url = 'www.example.com/video15637';
var video = url.split('/')[1];
alert(video)
OR
var url2 = 'http://www.example.com/video15637';
var video2 = url.substr(url.lastIndexOf('/') + 1);
alert(video2)
Combined DEMO
How I can get the URL portion of an URL using jQuery?
I have this URL: http://127.0.0.1/deposito/site/main/lojas.php. How I can get lojas.php?
You can use JavaScript and a regex to retrieve the file name like this:
function GetFilename(url){
if (url){
var m = url.toString().match(/.*\/(.+?)\./);
if (m && m.length > 1){
return m[1];
}
}
return "";
}
The above solution is more comprehensive, but something as simple as this would work in the majority of cases:
var filename = url.match(/.*\/(.+?)\./);
If you need to use jQuery, you can use the jQuery-URL-Parser plugin:
var file = $.url.attr("file");
Here's a link to the plugin:
https://github.com/allmarkedup/jQuery-URL-Parser
JavaScript:
var pathParts = window.location.pathname.split("/");
var file = pathParts[pathParts.length - 1];
alert(file);
If it's the document's current URL, you can "split-pop" document.location.pathname:
alert(document.location.pathname.split("/").pop());
//-> "lojas.php"
Otherwise, if you have the URL in a string you will need to remove any hash or query strings:
var url = "http://127.0.0.1/deposito/site/main/lojas.php"
alert(url.replace(/(?:\?|#).+/, "").split("/").pop());
//-> "lojas.php"