I'm trying to get the current directory of the file in Javascript so I can use that to trigger a different jquery function for each section of my site.
if (current_directory) = "example" {
var activeicon = ".icon_one span";
};
elseif (current_directory) = "example2" {
var activeicon = ".icon_two span";
};
else {
var activeicon = ".icon_default span";
};
$(activeicon).show();
...
Any ideas?
window.location.pathname will get you the directory, as well as the page name. You could then use .substring() to get the directory:
var loc = window.location.pathname;
var dir = loc.substring(0, loc.lastIndexOf('/'));
In Node.js, you could use:
console.log('Current directory: ' + process.cwd());
You can use window.location.pathname.split('/');
That will produce an array with all of the items between the /'s
complete URL
If you want the complete URL e.g. http://website/basedirectory/workingdirectory/ use:
var location = window.location.href;
var directoryPath = location.substring(0, location.lastIndexOf("/")+1);
local path
If you want the local path without domain e.g. /basedirectory/workingdirectory/ use:
var location = window.location.pathname;
var directoryPath = location.substring(0, location.lastIndexOf("/")+1);
In case you don't need the slash at the end, remove the +1 after location.lastIndexOf("/")+1.
directory name
If you only want the current directory name, where the script is running in, e.g. workingdirectory use:
var location = window.location.pathname;
var path = location.substring(0, location.lastIndexOf("/"));
var directoryName = path.substring(path.lastIndexOf("/")+1);
This will work for actual paths on the file system if you're not talking the URL string.
var path = document.location.pathname;
var directory = path.substring(path.indexOf('/'), path.lastIndexOf('/'));
For both / and \:
window.location.pathname.replace(/[^\\\/]*$/, '');
To return without the trailing slash, do:
window.location.pathname.replace(/[\\\/][^\\\/]*$/, '');
This one-liner works:
var currentDirectory = window.location.pathname.split('/').slice(0, -1).join('/')
An interesting approach to get the dirname of the current URL is to make use of your browser's built-in path resolution. You can do that by:
Create a link to ., i.e. the current directory
Use the HTMLAnchorElement interface of the link to get the resolved URL or path equivalent to ..
Here's one line of code that does just that:
Object.assign(document.createElement('a'), {href: '.'}).pathname
In contrast to some of the other solutions presented here, the result of this method will always have a trailing slash. E.g. running it on this page will yield /questions/3151436/, running it on https://stackoverflow.com/ will yield /.
It's also easy to get the full URL instead of the path. Just read the href property instead of pathname.
Finally, this approach should work in even the most ancient browsers if you don't use Object.assign:
function getCurrentDir () {
var link = document.createElement('a');
link.href = '.';
return link.pathname;
}
If you want the complete URL e.g. website.com/workingdirectory/ use:
window.location.hostname+window.location.pathname.replace(/[^\\\/]*$/, '');
window.location.pathname
I find this way pretty reliable to find the url of current page, by using the standard URL object. Fits well to create new URLs, using relative and absolute paths
url = window.location
console.log(url);
//strip pagename from pathname
currentdir = new URL(url.pathname.replace( /[^\/]*$/, ''), url.origin);
//now make new paths relative to currentdir
console.log(new URL("/dir1/dir2/hello.html", currentdir));
console.log(new URL("../../dir1/dir2/hello.html", currentdir));
console.log(new URL("../dir1/dir2/hello.html", currentdir));
console.log(new URL("./dir1/dir2/hello.html", currentdir));
console.log(new URL("dir1/dir2/hello.html", currentdir));
currentdir.port = 1234;
console.log(new URL("dir1/dir2/hello.html", currentdir));
There are current outputs expected, supposing the current page is
https://interactive-examples.mdn.mozilla.net/pages/js/string-replace.html
https://interactive-examples.mdn.mozilla.net/pages/js/string-replace.html
"currentdir = https://interactive-examples.mdn.mozilla.net/pages/js/"
https://interactive-examples.mdn.mozilla.net/dir1/dir2/hello.html
https://interactive-examples.mdn.mozilla.net/dir1/dir2/hello.html
https://interactive-examples.mdn.mozilla.net/pages/dir1/dir2/hello.html
https://interactive-examples.mdn.mozilla.net/pages/js/dir1/dir2/hello.html
https://interactive-examples.mdn.mozilla.net/pages/js/dir1/dir2/hello.html
https://interactive-examples.mdn.mozilla.net:1234/pages/js/dir1/dir2/hello.html
Related
I am try to get the data from the param in the URL
http://localhost:8080?test=1&redirectURL=http://localhost:8082/#/abc?param=1
I did
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
const redirectURL = urlParams.get('redirectURL'); // result: http://localhost:8082
but currently, the URL contain the hash code inside URL so the value return just http://localhost:8082
Is there any way to get full url http://localhost:8082/#/abc?param=1 by getting the param redirectURL
Thank you very much
I hope the following is useful for you.
var url_string = window.location.href;
var url = new URL(url_string);
var paramsTest = url.searchParams.get("test");
var paramsRedirectURL = url.searchParams.get("redirectURL");
console.log(paramsRedirectURL)
console.log(paramsTest)
Example here: https://codepen.io/yasgo/pen/dypWKoM
Maybe this can work for you
var afterHash = window.location.hash;
var beforeHash = window.location.href;
var fullURL = beforeHash ;
if(afterHash != '') // if there is something after hash and hash is exists in url then add the afterHash value in full url
{
var fullURL = beforeHash +"#"+ afterHash ;
}
console.log(fullURL);
I think the biggest issue here is that your redirectURL is not encoded. It should be encoded before it ends up in the URL, because otherwise the params and hashes from the nested URL are going to spill into the parent URL.
I obviously don't know if it would make sense for your project, but I think I would use domurl.
Maybe you should just use encodeURIComponent and possibly decodeURIComponent later, but I wanted to point out that domurl handles encoding and decoding automatically. Just as an example:
var url = new Url("http://localhost:8080?test=1");
url.query.redirectURL = 'http://localhost:8082/#/abc?param=1';
console.log( url.toString() );
// http://localhost:8080/?test=1&redirectURL=http%3A%2F%2Flocalhost%3A8082%2F%23%2Fabc%3Fparam%3D1
So again, what the encoded URL does is it prevents params from spilling from the nested URL to the parent URL and enables you to read redirectURL as a single string that you can then parse again to see/edit whatever params it has. The other important point is that I'm removing the hashtag with replace('/#/','/') in order to read the params from redirectURL:
Here's a slimmer jsfiddle where I'm just extracting the param and leave everything else out.
You'll definitely want to check dev tools consode log instead of the one stackoverflow offers, to make any sense of the objects.
console.log('');
// I'm encoding the redirectURL here, but in the real world it should be encoded before it's added as a parameter.
var url = new Url("http://localhost:8080?test=1&redirectURL="+ encodeURIComponent("http://localhost:8082/#/abc?param=1"));
console.log('url', url);
// So now that I've separated `url.query.redirectURL`, I can read that URL and its params separately...
var redirectUrl = new Url( url.query.redirectURL.replace('/#/', '/') ); // The hashtag is removed
console.log('redirectUrl:', redirectUrl );
console.log('redirectUrl - (param):', redirectUrl.query.param );
console.log('redirectUrl - path:', redirectUrl.path );
// If you need to use redirectURL without modifications you can just take the url param as is:
console.log( 'redirectUrl - no edits:', url.query.redirectURL );
// If you need to edit the params, you could do that and put just back the hashtag
redirectUrl.query.param = 'changed the param';
redirectUrl.path = '/#' + redirectUrl.path
console.log('redirectUrl - edited:', redirectUrl.toString() );
<script src="https://cdn.jsdelivr.net/npm/domurl#2.3.4/url.min.js"></script>
I'm trying to do a simple string replace in jquery but it seems to be more than just a simple code.
In mygallery have this image link (note the 2x ../)
var imgName= '../../appscripts/imgs/pic_library/burn.jpg';
In browsegallery I have something like this:
var imgName ='../../../../../appscripts/imgs/pic_library/burn.jpg';
and sometimes depending on where do I get the image source from, it can be like this
var imgName = '../appscripts/imgs/pic_library/burn.jpg';
What I'm trying to do is, to get rid of all of those '../', and to gain the imgName like this:
'appscripts/imgs/pic_library/burn.jpg';
So this way I can get the right directory for my mobile app.
Can anyone help me on how to get rid of all those (without even counting) '../'?
Best Regards!
Using the replace method of a string you can remove all cases of the
../
var imgPath = '../../../../../appscripts/imgs/pic_library/burn.jpg';
var imgName = imgPath.replace(/\.\.\//g, '');
console.log(imgName);
Here is a direct answer to your question that does not tie you to the "/appscripts" in your example:
const imgName= '../../appscripts/imgs/pic_library/burn.jpg';
const img = imgName.split('../')
.filter((val) => val !== '')
.join('');
If the desired end path is always the same - just get the unique part (the actual file name) and add it to a string of the path you require. the following usies lastIndexOf to get the actual file name from the relative path and then builds a string to give the desired path plus the file name.
var fileSource = 'appscripts/imgs/pic_library/burn.jpg';
let lastIndex = fileSource.lastIndexOf('/');
let fileName = fileSource.slice(lastIndex + 1, fileSource.length); // gives burn.jpg
let imageSource = 'appscripts/imgs/pic_library/' + fileName;
console.log(imageSource); // gives appscripts/imgs/pic_library/burn.jpg
Thank you all for helping me out.
I finally solved this using imgName.split('/appscripts/');
Like this:
var replaceImg = image.split('/appscripts/');
var finalImageName = "../../../appscripts/"+replaceImg[1];
Thank you again!
You can create a jQuery plugin, i.e: $(...).imagify()
Use a regex to replace that pattern: .replace(/(\.){1,2}\//g, '')
$.fn.imagify = function() {
var src = this.attr('src') || '';
this.attr('src', src.replace(/(\.){1,2}\//g, ''));
};
$('img').imagify();
$('img').each((_, obj) => console.log($(obj).attr('src')));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src='../../../../../appscripts/imgs/pic_library/burn.jpg'>
<img src='../appscripts/imgs/pic_library/burn.jpg'>
<img src='./../../appscripts/imgs/pic_library/burn.jpg'>
Resource
How to Create a Basic Plugin
I have two paths in Node.js, e.g.:
var pathOne = '/var/www/example.com/scripts';
var pathTwo = '/var/www/example.com/scripts/foo/foo.js';
How do I subtract one path from another in order to obtain a relative path?
subtractPath(pathTwo, pathOne); // => 'foo/foo.js'
Is there a module that does this according to all necessary URL rules or do I better use some simple string manipulations?
Not sure what you mean by "according to all necessary URL rules", but it seems you should be able to just use path.relative;
> var pathOne = '/var/www/example.com/scripts';
> var pathTwo = '/var/www/example.com/scripts/foo/foo.js';
> path.relative(pathOne, pathTwo)
'foo/foo.js'
> path.relative(pathTwo, pathOne)
'../..'
You can do that easily with a regex:
var pathOne = /^\/your\/path\//
var pathTwo = '/your/path/appendix'.replace(pathOne, '');
This way you can force it to be at the start of the second path (using ^) and it won't be erased if it isn't an exact match.
Your example would be:
var pathOne = /^\/var\/www\/example.com\/scripts\//;
var pathTwo = '/var/www/example.com/scripts/foo/foo.js'.replace(pathOne, '');
It should return: foo/foo.js.
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));
})()
Is it possible to get the filename without the extension from the src filepath.
As an example, let's say the src file is my-file.png - located at images/my-file.png.
In my task I have this at the moment:
var processName = options.processName || function (name) { return name; };
var filename = processName(filepath);
When I reference filename for output it returns:
images/my-file.png
I want to only return the actual filename, without the path and without the extension:
my-file.png
How can I achieve this?
Might be pretty old but if someone else finds this SO., in reply for #user3143218 's comment :
slice(0, -4) will remove the last 4 characters from the name, so for the example my-file.png we will get my-file but for script.js we will get scrip. I suggest using a regex removing everything from the last dot.
You could use a regex like this:
var theFile = filename.match(/\/([^/]*)$/)[1];
var onlyName = theFile.substr(0, theFile.lastIndexOf('.')) || theFile;
That should give you my-file. The regex gives you the string after the last forward slash, and the next line removes everything after the last dot (and the dot).
Thanks to Andeersg's answer below I was able to pull this off. It might not be the best solution but it works. Final code is:
var processName = options.processName || function (name) { return name; };
var filename = processName(filepath);
var theFile = filename.match(/\/([^/]*)$/)[1];
var onlyName = theFile.slice(0, -4);
Now onlyName will return:
my-file