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.
Related
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
This is my first question on stack overflow.
I need to create a path for images and path should be like this pages/assets/images/Topic02/T02P08/L1T2_P8_2a_Normal.png . So I am breaking this string into 2 parts.
1st
var dummyUrl1= "pages/assets/images/Topic02/T02P08/L1T2_P8_2";
2nd
var dummyUrl2="_Normal.png";
I just need to change 2a with 2b,2c,2d etc according to my need. So I stored these letters into an array. And picking them. And then I am making a new string string in this manner,
var currentImgUrl= dummyUrl1+arr[imageId]+dummyUrl2;
where arr=['a','b','c','d','e']
So value of currentImgUrl should be like this,
"pages/assets/images/Topic02/T02P08/L1T2_P8_2b_Normal.png" but I am getting value in this manner ,
"http://192.168.86.91/Tarun/AXON/DfMAWorking/pages/assets/images/Topic02/T02P08/L1T2_P8_2a_Normal.png"
I tried this code:
$(".clickme,.innerText").mouseenter(function(){
var arr = ['a','b','c','d','e'];
var dummyUrl1= "pages/assets/images/Topic02/T02P08/L1T2_P8_2";
var dummyUrl2="_Normal.png";
var getImageId = $(this).attr("id");
var imageId= getImageId.substring(3,4);
var currentImgUrl= dummyUrl1+arr[imageId]+dummyUrl2;
console.log("Current Image should be : "+currentImgUrl);
});
Your URL is relative, if you want http://192.168.86.91/pages/assets/...Normal.png", add a / at the beginning of dummyUrl1 dummyUrl1= "/pages/assets/images/Topic02/T02P08/L1T2_P8_2";
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);
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
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