I have to extract a specific part from an url origin. But I can't seem to figure out a good and fail proof way to do this
For example, this is my url:
http://site.domain.com
I need to know what "domain" is used. How do I get this part from the url 100% of the time?
My first thought was to split it between the "." but then I thought about what could happen if someone uses a http://www.site.domain.com link. That would mean it wouldn't work.
Further explanation:
I currently have 2 website which both have a differend domain name. I have to get the information about which page is loaded, based on the "domain" name in the url.
Thanks in regard!
split the full domain name on dot and than take element before last element.
var url = 'http://www.site.domain.com';
var array = url.split(".");
var lengthOfArray = array.length;
var domain = array[lengthOfArray-2];
console.log(domain);
Split by / using split("/"):
function getDomain(url){
var arr = url.split(".");
return arr[arr.length - 2];
}
console.log(getDomain('http://site.domain.com'));
console.log(getDomain('http://www.site.domain.com'));
You could split it by "." and get the next to last text of your string.
var str = 'http://www.site.domain.com';
var domain = str.split('.');
console.log(domain[domain.length-2]);
Later Edit
To provide further fail proof, you can get the latest text between .com and the first dot before it. This will work in case you have another dot in your URL, for example: 'http://www.site.domain.com/post/test.asp'.
var str = 'http://www.site.domain.com/post/test.asp';
var preComLink = str.substr(0, str.indexOf('.com'));
var preDomainIndex = preComLink.lastIndexOf('.');
var domain = preComLink.substr(preDomainIndex + 1, str.indexOf('com'));
console.log(domain);
let code = (function(){
return{
getDomain: function(url){
var slpitDomainURL = url.split(".");
var lengthOfArray = slpitDomainURL.length;
var domain = slpitDomainURL[lengthOfArray-2];
return domain;
}
}
})();
console.log(code.getDomain('http://www.google.com'));
console.log(code.getDomain('http://www.facebook.com'));
Related
I have this URL
https://myApp-ajj.com/sp?id=cat_item&sys_id=cf9f149cdbd25f00d080591e5e961920&sys_id1=cf9f149cdbd25f00d080591e5e961920&sysp_Id=a691acd9dbdf1bc0e9619fb&sysparm_CloneTable=sc_request&sysparm_CloneTable=sc_request
Here I am getting sys_id two times with different parameters. So I need to remove the second & sign and all text after that.
I tried this
location.href.split('&')[2]
I am sure it doesn't work. Can anyone provide some better solution?
Firstly, you should split the string into an array then use slice to set the starting index number of the element which is 2 in your case and then join the array again into the string.
Read more about these methods JavaScript String split() Method, jQuery slice() Method and JavaScript Array join() Method
var url = 'https://myApp-ajj.com/sp?id=cat_item&sys_id=cf9f149cdbd25f00d080591e5e961920&sys_id=cf9f149cdbd25f00d080591e5e961920&sysp_Id=a691acd9dbdf1bc0e9619fb&sysparm_CloneTable=sc_request&sysparm_CloneTable=sc_request';
url = url.split("&").slice(0,2).join("&");
console.log(url);
Maybe like this:
var url='https://myApp-ajj.com/sp?id=cat_item&sys_id=cf9f149cdbd25f00d080591e5e961920&sys_id=cf9f149cdbd25f00d080591e5e961920&sysp_Id=a691acd9dbdf1bc0e9619fb&sysparm_CloneTable=sc_request&sysparm_CloneTable=sc_request';
var first=url.indexOf('&');
var second=url.indexOf('&',first+1);
var new_url=url.substring(0,second);
console.log(new_url);
You need to find the 2nd occurrence of &sys_id. From there onwards remove all text.
Below is working code:
let url='https://myApp-ajj.com/sp?id=cat_item&sys_id=cf9f149cdbd25f00d080591e5e961920&sys_id=cf9f149cdbd25f00d080591e5e961920&sysp_Id=a691acd9dbdf1bc0e9619fb&sysparm_CloneTable=sc_request&sysparm_CloneTable=sc_request';
let str1=url.indexOf('&sys_id');
let str2=url.indexOf('&sys_id',str1+1);
console.log(url.substring(0,str2));
This is a bit more verbose, but it handles all duplicate query params regardless of their position in the URL.
function removeDuplicateQueryParams(url) {
var params = {};
var parsedParams = '';
var hash = url.split('#'); // account for hashes
var parts = hash[0].split('?');
var origin = parts[0];
var retURL;
// iterate over all query params
parts[1].split('&').forEach(function(param){
// Since Objects can only have one key of the same name, this will inherently
// filter out duplicates and keep only the latest value.
// The key is param[0] and value is param[1].
param = param.split('=');
params[param[0]] = param[1];
});
Object.keys(params).forEach(function(key, ndx){
parsedParams += (ndx === 0)
? '?' + key +'='+ params[key]
: '&' + key +'='+ params[key];
});
return origin + parsedParams + (hash[1] ? '#'+hash[1] : '');
}
console.log( removeDuplicateQueryParams('http://fake.com?q1=fu&bar=fu&q1=fu&q1=diff') );
console.log( removeDuplicateQueryParams('http://fake.com?q1=fu&bar=fu&q1=fu&q1=diff#withHash') );
var url = "https://myApp-ajj.com/sp?id=cat_item&sys_id=cf9f149cdbd25f00d080591e5e961920&sys_id1=cf9f149cdbd25f00d080591e5e961920&sysp_Id=a691acd9dbdf1bc0e9619fb&sysparm_CloneTable=sc_request&sysparm_CloneTable=sc_request"
url = url.slice(0, url.indexOf('&', url.indexOf('&') + 1));
console.log(url);
Try this :)
Try this:
var yourUrl = "https://myApp-ajj.com/sp?id=cat_item&sys_id=cf9f149cdbd25f00d080591e5e961920&sys_id=cf9f149cdbd25f00d080591e5e961920&sysp_Id=a691acd9dbdf1bc0e9619fb&sysparm_CloneTable=sc_request&sysparm_CloneTable=sc_request"
var indexOfFirstAmpersand = yourUrl.search("&"); //find index of first &
var indexOfSecondAmpersand = indexOfFirstAmpersand + yourUrl.substring((indexOfFirstAmpersand + 1)).search("&") + 1; //get index of second &
var fixedUrl = yourUrl.substring(0, indexOfSecondAmpersand)
$(".answer").text(fixedUrl);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="answer">
</p>
You can manipulate the url using String.prototype.substring method. In the example below I created a function that takes a url string and checks for a duplicate parameter - it returns a new string with the second occurrence removed.
var url = "https://myApp-ajj.com/sp?id=cat_item&sys_id=cf9f149cdbd25f00d080591e5e961920&sys_id=cf9f149cdbd25f00d080591e5e961920&sysp_Id=a691acd9dbdf1bc0e9619fb&sysparm_CloneTable=sc_request&sysparm_CloneTable=sc_request";
function stripDuplicateUrlParameter(url, parameterName) {
//get the start index of the repeat occurrance
var repeatIdx = url.lastIndexOf('sys_id');
var prefix = url.substring(0, repeatIdx);
var suffix = url.substring(repeatIdx);
//remove the duplicate part from the string
suffix = suffix.substring(suffix.indexOf('&') + 1);
return prefix + suffix;
}
console.log(stripDuplicateUrlParameter(url));
This solves your specific problem, but wouldn't work if the parameter occurred more than twice or if the second occurrence of the string wasn't immediately following the first - you would probably write something more sophisticated.
As someone already asked - why is the url parameter being duplicated in the string anyway? Is there some way to fix that? (because the question asked seems to me to be a band-aid solution with this being the root issue).
I have an url that looks like this:
http://localhost/assets/upload/img/hw6dNDBT-36x36.jpg
I want to extract hw6dNDBT.jpg, from the url above.
I tried playing around with regex patterns /img\/.*-/ but that
matches with img/hw6dNDBT-.
How can I do this in JavaScript?
try this:
var url = 'http://localhost/assets/upload/img/hw6dNDBT-36x36.jpg';
var filename = url.match(/img\/(.*)-[^.]+(\.[^.]+)/).slice(1).join('');
document.body.innerHTML = filename;
i would use split() method:
var str = "http://localhost/assets/upload/img/hw6dNDBT-36x36.jpg";
var strArr = str.split("/");
var size = strArr.length - 1;
var needle = strArr[size].split("-");
var fileTypeArr = strArr[size].split(".");
var name = needle[0]+"."+fileTypeArr[fileTypeArr.length-1];
name should now be your searched String so far it contains no / inside it
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split
/[^\/]+$/ should match all characters after the last / in the URL, which seems to be what you want to match.
No regex:
//this is a hack that lets the anchor tag do some parsing for you
var parser = document.createElement('a');
parser.href = 'http://localhost/assets/upload/img/hw6dNDBT-36x36.jpg';
//optional if you know you can always trim the start of the path
var path = parser.pathname.replace('/assets/uploads/');
var parts = path.split('/');
var img = '';
for(var i=0; i<parts.length; i++) {
if (parts[i] == 'img') {
//since we know the .jpg always follows 'img/'
img = parts[i+1];
}
}
Ah, you were so close! You just need to take your regex and use a capturing group, and then add a littttle bit more!
img\/(.*)-.*(\..*)
So, you can use that in this manner:
var result = /img\/(.*)-.*(\..*)/.exec();
var filename = result[1] + result[2];
Honestly capturing the .jpg, is a little excessive, if you know they are all going to be JPG images, you can probably just take out the second half of the regex.
Incase you are wondering, why do we uses result[1] and result[2]? Because result[0] stores the entire match, which is what you were getting back. The captured groups, which is what we create when we use the parentheses, are stored as the indexes after 0.
Here is some one-liner:
var myUrl = 'http://localhost/assets/upload/img/hw6dNDBT-36x36.jpg',
myValue = myUrl.split('/').pop().replace(/-(?=\d).[^.]+/,'');
We take everything after the last slash then cut out the dimension part.
I want to parse some urls's which have the following format :-
var url ="http://www.example.com/cooks/cooking-dress-wine/~no-order/pr?p%5B%5D=sort%3Dfeatured&sid=bks%2C43p&mycracker=ch_vn_clothing_subcategory_Puma&ref=b41c8097-8efe-4acf-8919-0fa81bcb590a"
Its not necessary that the domain name and other parts would be same for all url's, they can vary i.e I am looking at a general solution.
Basically I want to strip off all the other things and get only the part:
/cooks/cooking-dress-wine/~no-order/pr?p%5B%5D=sort%3Dfeatured&sid=bks%2C43p
I thought to parse this using JavaScript and Regular Expression
I am doing like this:
var mapObj = {"/^(http:\/\/)?.*?\//":"","(&mycracker.+)":"","(&ref.+)":""};
var re = new RegExp(Object.keys(mapObj).join("|"),"gi");
url = url.replace(re, function(matched){
return mapObj[matched];
});
But its returning this
http://www.example.com/cooks/cooking-dress-wine/~no-order/pr?p%5B%5D=sort%3Dfeatured&sid=bks%2C43pundefined
Where am I not doing the correct thing? Or is there another approach with an even easier solution?
You can use :
/(?:https?:\/\/[^\/]*)(\/.*?)(?=\&mycracker)/
Code :
var s="http://www.example.com/cooks/cooking-dress-wine/~no-order/pr?p%5B%5D=sort%3Dfeatured&sid=bks%2C43p&mycracker=ch_vn_clothing_subcategory_Puma&ref=b41c8097-8efe-4acf-8919-0fa81bcb590a";
var ss=/(?:https?:\/\/[^\/]*)(\/.*?)(?=\&mycracker)/;
console.log(s.match(ss)[1]);
Demo
Fiddle Demo
Explanation :
Why don't you just map a split array?
You don't quite need to regex the URL, but you will have to run an if statement inside the loop to remove specific GET params from them. In this particular case (key word particular) you just have to substring till the indexOf "&mycracker"
var url ="http://www.example.com/cooks/cooking-dress-wine/~no-order/pr?p%5B%5D=sort%3Dfeatured&sid=bks%2C43p&mycracker=ch_vn_clothing_subcategory_Puma&ref=b41c8097-8efe-4acf-8919-0fa81bcb590a"
var x = url.split("/");
var y = [];
x.map(function(data,index) { if (index >= 3) y.push(data); });
var path = "/"+y.join("/");
path = path.substring(0,path.indexOf("&mycracker"));
Change the following code a little bit and you can retrieve any parameter:
var url = "http://www.example.com/cooks/cooking-dress-wine/~no-order/pr?p%5B%5D=sort%3Dfeatured&sid=bks%2C43p&mycracker=ch_vn_clothing_subcategory_Puma&ref=b41c8097-8efe-4acf-8919-0fa81bcb590a"
var re = new RegExp(/http:\/\/[^?]+/);
var part1 = url.match(re);
var remain = url.replace(re, '');
//alert('Part1: ' + part1);
var rf = remain.split('&');
// alert('Part2: ' + rf);
var part2 = '';
for (var i = 0; i < rf.length; i++)
if (rf[i].match(/(p%5B%5D|sid)=/))
part2 += rf[i] + '&';
part2 = part2.replace(/&$/, '');
//alert(part2)
url = part1 + part2;
alert(url);
var url ="http://www.example.com/cooks/cooking-dress-wine/~no-order/pr?p%5B%5D=sort%3Dfeatured&sid=bks%2C43p&mycracker=ch_vn_clothing_subcategory_Puma&ref=b41c8097-8efe-4acf-8919-0fa81bcb590a";
var newAddr = url.substr(22,url.length);
// newAddr == "/cooks/cooking-dress-wine/~no-order/pr?p%5B%5D=sort%3Dfeatured&sid=bks%2C43p&mycracker=ch_vn_clothing_subcategory_Puma&ref=b41c8097-8efe-4acf-8919-0fa81bcb590a"
22 is where to start slicing up the string.
url.length is how much of it to include.
This works as long as the domain name remains the same on the links.
I have a url like this
http://example.com/param1/param2/param3
Please help me get the second last parameter using javascript. I searched and could only find regex method to find the last parameter. I am new to this. Any help would be greatly appreciated.
Thanks.
var url = 'http://example.com/param1/param2/param3';
var result= url.split('/');
var Param = result[result.length-2];
Demo Fiddle:http://jsfiddle.net/HApnB/
Split() - Splits the string into an array of strings based on the separator you mentioned
In the above , result will be an array that contains
result = [http:,,example.com,param1,param2,param3];
Basic string operations:
> 'http://example.com/param1/param2/param3'.split('/').slice(-2)[0]
"param2"
You can do this by:
document.URL.split("/");
var url='http://example.com/param1/param2/param3';
var arr = url.split('/');
alert(arr[arr.length-2]);
arr[arr.length-2] will contain value 'param2'. Second last value
var url = "http://example.com/param1/param2/param3";
var params = url.replace(/^http:\/\/,'').split('/'); // beware of the doubleslash
var secondlast = params[params.length-2]; // check for length!!
var url = "http://example.com/param1/param2/param3";
var split = url.split("/");
alert(split[split.length - 2]);
Demo: http://jsfiddle.net/gE7TW/
The -2 is to make sure you always get the second last
My favorite answer is the following from #Blender
'http://example.com/param1/param2/param3'.split('/').slice(-2)[0]
However all answers suffer from the edge case syndrome. Below are the results of applying the above to a number of variants of your input string:
"http://example.com/param1/param2/param3" ==> "param2"
"http://example.com/param1/param2" ==> "param1"
"http://example.com/param1/" ==> "param1"
"http://example.com/param1" ==> "example.com"
"http://example.com" ==> ""
"http://" ==> ""
"http" ==> "http"
Note in particular the cases of the trailing /, the case with only // and the case with no /
Whether these edge cases are acceptable is something you will need to determine within the larger context of your code.
Do not validate this answer, choose from amongst the others.
Just another alternate solution:
var a = document.createElement('a');
a.href = 'http://example.com/param1/param2/param3'
var path = a.pathname;
// get array of params in path
var params = path.replace(/^\/+|\/+$/g, '').split('/');
// gets second from last parameter; returns undefined if not array;
var pop = params.slice(-2)[0];
I need to parse long urls and set a variable (category) equal to one of the /folders/ in the path.
For example, a url that is
http://example.com/community/home/whatever.html
I need to set the variable equal to whatever folder path comes after /home/ in that url.
I've got this to alert me with what comes after /community/, but then the url turns to NaN and the link doesnt work. I think I'm not on the right track.
if ($(this.href*='http://example.com/community/')){
var category = url.split("community/");
alert(category[category.length - 1]);
}
Thoughts?
TIA.
You can fetch everything after the "/community/" with a regular expression:
var url = "http://www.example.com/community/whatever";
var category = "";
var matches = url.match(/\/community\/(.*)$/);
if (matches) {
category = matches[1]; // "whatever"
}
Working example here: http://jsfiddle.net/jfriend00/BL4jm/
If you want to get only the next path segment after community and nothing after that segment, then you could use this:
var url = "http://www.example.com/community/whatever/more";
var category = "";
var matches = url.match(/\/community\/([^\/]+)/);
if (matches) {
category = matches[1]; // "whatever"
} else {
// no match for the category
}
Workikng example of this one here:http://jsfiddle.net/jfriend00/vrvbT/
When you do this.href*= you're doing multiplication, and that's why you're getting not-a-number. It multiplies this.href by the string and assigns that to href.
If you mean to test whether the url starts with that string you can do it like this, no need for jQuery:
var start = 'http://example.com/community/';
if (url.substring(0, start.length) === start)){
var category = url.split("community/");
var lastPart = category[category.length - 1];
return lastPart.split("/")[0];
}