Get File Name and Parent Folder of URL - javascript

This javascript will get the whole path and the file name however the idea is to retrieve the file name + extension and its parent folder so it returns this:
/thisfolder/thanks.html
var url = "www.example.com/get/thisfolder/thanks.html";
var path = url.substring(url.indexOf('/')+1, url.lastIndexOf('.'));
alert(path)
JS Fiddle

Using .split(), you can select the last 2 elements and join them together after:
var url = "www.example.com/get/thisfolder/thanks.html";
var path = url.split('/').slice(-2).join('/');
alert(path);

You could split by /:
var parts = url.split("/");
var filename = parts.pop();
var parent = parts.pop();

Here is an alternative using array:
var paths = url.split("/");
var path = paths[paths.length - 2] + "/" + paths[paths.length - 1];

Related

How to strip / replace something from a URL?

I have this URL
http://192.168.22.124:3000/temp/box/c939c38adcf1873299837894214a35eb
I want to replace the last part of my URL which is c939c38adcf1873299837894214a35eb with something else.
How can I do it?
Try this:
var url = 'http://192.168.22.124:3000/temp/box/c939c38adcf1873299837894214a35eb';
somethingelse = 'newhash';
var newUrl = url.substr(0, url.lastIndexOf('/') + 1) + somethingelse;
Note, using the built-in substr and lastIndexOf is far quicker and uses less memory than splitting out the component parts to an Array or using a regular expression.
You can follow this steps:
split the URL with /
replace the last item of array
join the result array using /
var url = 'http://192.168.22.124:3000/temp/box/c939c38adcf1873299837894214a35eb';
var res = url.split('/');
res[res.length-1] = 'someValue';
res = res.join('/');
console.log(res);
Using replace we can try:
var url = "http://192.168.22.124:3000/temp/box/c939c38adcf1873299837894214a35eb";
var replacement = 'blah';
url = url.replace(/(http.*\/).*/, "$1" + replacement);
console.log(url);
We capture everything up to and including the final path separator, then replace with that captured fragment and the new replacement.
Complete guide:
// url
var urlAsString = window.location.href;
// split into route parts
var urlAsPathArray = urlAsString.split("/");
// create a new value
var newValue = "routeValue";
// EITHER update the last parameter
urlAsPathArray[urlAsPathArray.length - 1] = newValue;
// OR replace the last parameter
urlAsPathArray.pop();
urlAsPathArray.push(newValue);
// join the array with the slashes
var newUrl = urlAsPathArray.join("/");
// log
console.log(newUrl);
// output
// http://192.168.22.124:3000/temp/box/routeValue
You could use a regular expression like this:
let newUrl = /^.*\//.exec(origUrl)[0] + 'new_ending';

How to get file path when I input a full filename in javascript?

I hope to get the path of a filename, just like get the result /storage/emulated/0/Pictures/ when I input the string /storage/emulated/0/Pictures/Photo-2017-02-17-10-08-38_2271.JPG
How can I do in javascript? Thanks!
Try
var fullpath = "/storage/emulated/0/Pictures/Photo-2017-02-17-10-08-38_2271.JPG"
var pathWithoutFileName = fullpath.substr(0, fullpath.lastIndexOf('/') + 1);
var x = "/storage/emulated/0/Pictures/Photo-2017-02-17-10-08-38_2271.JPG"
var path = x.substr(0,x.lastIndexOf('/'));
var fullpath = "/storage/emulated/0/Pictures/Photo-2017-02-17-10-08-38_2271.JPG"
var path = fullpath.substr(0, fullpath.lastIndexOf('/') + 1);
The +1 is to include the last forward slash.

How to parse a url using Javascript and Regular Expression?

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.

extract part of URL from parent URL

For this url
"http://testsite/sites/TestSubSite/objstrat/CultureConnection/Pages/default.aspx"
Trying to extract everything after enterprise/sites.
I want "/TestSubSite/objstrat/CultureConnection/Pages/default.aspx"
I can get the filename like this:
var filename = parenturl.substring(parenturl.lastIndexOf("/") + );
But not sure how to extract from the middle..
Using lastIndexOf will fail for any URI reference with / in the fragment or query, as in http://example.com/foo/bar#/baz/boo.
Libraries like Google Closure's Uri module can make this easy.
new goog.Uri(parenturl).getPath()
If your library of choice doesn't have URI support, then http://www.ietf.org/rfc/rfc3986.txt appendix B suggests
var urlRegex = /^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;
var path = decodeURIComponent(urlRegex.exec(parenturl)[5]);
will get you the path part.
Once you've got the path, you can then strip off the /sites/ part by doing something like
var pathSuffix = path.replace(/^\/sites\//, '/');
I love Javascript with DOM element.
var link = document.createElement('a');
link.href = "http://testsite/sites/TestSubSite/objstrat/CultureConnection/Pages/default.aspx";
link.protocol;
link.hostname;
link.port;
link.pathname;
link.search;
link.hash;
link.host;
link.pathname.replace(/^\/sites/,"") // "/TestSubSite/objstrat/CultureConnection/Pages/default.aspx"
The easiest thing might be to use javascript's Split() function and rebuild the string from the resulting array (leaving out the first couple items)
var parenturl = "http://testsite/sites/TestSubSite/objstrat/CultureConnection/Pages/default.aspx";
var tokens = parenturl.split("/");
for(var i=0;i<tokens .length;i++)
{
console.log(tokens [i]);
}
Hows about:
var parenturl = "http://testsite/sites/TestSubSite/objstrat/CultureConnection/Pages/default.aspx";
var filename = parenturl.match(/\/sites(.*)$/)[1];
alert(filename);

Javascript parsing Url

I have a Url which is like this.
https://testOne.abcd.com/myOrders/OrderList/Order123.aspx
How do I get only Order123 ?
I used window.location.href.split('/')[5].split('/')[1]
how do i set it dynamically?
TIA
if you want to use substr string method..
var filename = url.substr(url.lastIndexOf('/')+1) // -> 'Order123.aspx'
var filename_noext = filename.substr(0, filename.lastIndexOf('.')) // -> 'Order123'
If you want to get the file name, minus the extension, this will work.
var regex = /.*\/([^\/]+)\.aspx/;
var url = 'https://testOne.abcd.com/myOrders/OrderList/Order123.aspx'
var match = regex.exec(url);
var fileName = match[1];
alert(fileName); // This will output "Order123"

Categories