Is this even possible to get specific file path from url
my file path is like
testing\abc\pqr\subfolder1\anotherFolder
or
testing\sufolder\anothersubfolder\abc\pqr\xyz\mno
my output will look like this
testing\abc\pqr
or
testing\sufolder\anothersubfolder\abc
Its should remove last few name of a folder and provide only specific length folder name from the start of the path which I will pass in an array
You can split the path and just grab the number of segments you want from the front. Since you're showing Windows-style paths, here's some sample code that uses the Windows path separator. This can be adapted to use path.sep if you want a cross platform version. Since your example paths do not start with a leading slash, this code assumes that.
function getFrontPathSegments(fullPath, numSegments) {
let pieces = fullPath.split("\\");
return pieces.slice(0, numSegments).join("\\");
}
// example usage
let front = getFrontPathSegments("testing\\sufolder\\anothersubfolder\\abc\\pqr\\xyz\\mno", 3);
console.log(front);
Related
I'm currently developing a site in which a user can create a user area with a user directory created at registration such as myWebsite.com/user/myUserName
Now I've seen YouTube & TikTok (and presumably more) use an url like myWebsite.com/user/#myUserName (note the "#")
So my question is how do I read these? if a user visits myWebsite.com/user/#myUserName how do I read the # data?
I've searched many SO questions and Google before asking this and can't seen to find answers. only for standard url params or hashtags but not #, help!
Solution
You can use the window.location.pathname API to read the path name, parse it into an array and then filter out the only item that starts with an "#" character.
// take the entire path from the window and split them into an array with /
const paths = window.location.pathname.split('/')
// paths = ["","user","#myUserName"]
// pick out the first item in the array starting with an "#:
const userName = paths.find((item) => item.at(0) === "#")
// userName = "#myUserName"
Explanation
Firstly, you need to understand the structure of a URL https://developer.mozilla.org/en-US/docs/Learn/Common_questions/What_is_a_URL
Looking at your example, the user id should be part of the path. To get the entire path of /my-path/#user-id, you can use window.location.pathname (MDN reference).
From there on, you can parse the path to get the user id with JavaScript
Alternative Answer
Or you can just use Regex and capture anything that comes after "#"
const final = window.location.pathname.match("#.*").at(0)
// note: not a complete solution because it captures the other parts of the URL following the `/#username/` path
I have a text like this:
Last login: today
cat file
testMachine:root:/root# cat file
File contents
testMachine:root:/root#
And I need to retrieve the information like this:
testMachine:root:/root# cat file
File contents
Stripping away the last line is easy, but the amount of lines I need to remove at start is arbitrary, and I need to remove everything up until the first cue word, which is the machine name, that is known and stored.
I have tried substring() but it strips line by line instead of treating the whole text as one, and removes the host name too, which should remain there. I tried replace() too, but I am not familiar with regex, so the result is a memory exception.
EDIT 1: It seems to be important to note that using a JS for Java engine (In this case I'm using Rhino) means the result isn't the same as you get in web. This was found out after an answer below, which works perfectly on web, doesn't even run on the desktop app.
const text = `
Last login: today
cat file
testMachine:root:/root# cat file
File contents
testMachine:root:/root#`;
const cueWord = "testMachine:root"
const idx = text.indexOf(cueWord);
let restOftheString = text.substring(idx).split("\n");
restOftheString.pop()
console.log(restOftheString.join("\n"))
I'm trying to use jQuery so that when somebody goes to this exact page: www.mysite.com/somedirectory/somesubdirectory divwhite appears and divgrey is hidden. This code works. However, I was wondering if there is someway to write the code so that it checks to see if somesubdirectory is two directories lower than the root level and not dependent if somedirectory is there or not in case somedirectory's name changes.
$(document).ready(function() {
var myvariable = $(location).attr('href');
if(myvariable.indexOf("/somedirectory/somesubdirectory") > -1) {
$("#divgrey").hide();
$("#divwhite").show();
}
else {
j$("#divgrey").show();
$("#divwhite").hide();
}
});
You could use one line of vanilla JavaScript
window.location.pathname.split('/').length
If this number equals 3, the path name contains two slashes and you are in a subdirectory two levels below the root directory, independent of their names.
Note that this assumes that you take care of trailing slashes in the URL in your .htaccess.
I am writing a photoshop script in JS, at this point I ask the user to select and folder location and add all those files to an array. I wish to then parse the array so only the filename remains.
I get this error : fileList[i].replace is not a function
I imagine its due to me passing in the wrong value or using the wrong type. Was hoping someone could explain the issue and help me resolve it please?
//Prompt for folder location
var Path = Folder.selectDialog("Select Folder Location for Renders")
// Use the path to the application and append the samples folder
var samplesFolder = Folder(Path)
var fileList = samplesFolder.getFiles()
for (var i = 0; i < fileList.length; i++)
{
fileList[i] = fileList[i].replace(/^.*[\\\/]/, '')
}
prompt("Complete")
Thanks for your time, AtB
S
The error is occuring because you're expecting a string, and it isn't one.
http://jongware.mit.edu/idcs5js_html_3.0.3i/idcs5js/pc_Folder.html says that getFiles
returns an array of File and Folder objects, or null if this object's referenced folder does not exist.
Fortunately, both File and Folder have these properties:
fsName - The platform-specific full path name for the referenced file
fullName - The full path name for the referenced file in URI notation.
name - The file name portion of the absolute URI for the referenced file, without the path specification
Of course, if you don't want any of the path, and just want the filename, use name, otherwise, use the replace command on whichever suits you - fsName or fullName.
So - in your loop, you want:
fileList[i] = fileList[i].name
You may want to filter out the Folders in your end result. That would entail something like this inside your loop:
if (fileList[i] instanceof Folder) {
fileList.splice(i, 1);
--i; // go back one i, because you just removed an index. Note, if you're not careful, such shenanigans may mess up the second term of the for loop.
continue;
}
One last suggestion: I would personally find it cleaner to make a new array, rather than doing the replacement in position. The language certainly supports what you're doing, but it still makes me twitch to go from File or Folder array to string array. (Granted, you thought you were doing string array to string array.) This would also simplify any issues with removing indices for folders, etc.
I have folder/file tree generated by JavaScript where the folder and files each have checkbox inputs with paths associated with them, like:
/var/www/site/user/folder7/ or
/var/www/site/user/folder7/file.txt or
/var/www/site/user/folder7/file.? (? being any file extension)
In the case of these paths I need only
/var/www/site/user/folder7
I know that normally to remove file names one would use something like:
var full_path = node.context.nextElementSibling.value;
var folder_target_path = full_path.substring(0, full_path.lastIndexOf("/"));
However this return either:
/var/www/site/user/folder7 or
/var/www/site/user
I could use the lastIndexOf() method if I could use some regex to find .? and then up to the last '/'; however I am fairly new to javascript and have never used regex in it.
Could you suggest an effecient way to get only the folder and not the file path in all cases?
Regards,
Steve
Here's the W3 tutorial on JavaScript and regex:
http://www.w3schools.com/jsref/jsref_obj_regexp.asp
var folder_target_path = full_path.replace(/\/[^\/]*$/, '');
will remove the last / and anything following it. I think you can avoid having to escape the /'s in the pattern by creating a Regexp object from a string.
To get this working completely I need to use the following:
var full_path = node.context.nextElementSibling.value;
var folder_target_path;
var pathRE = /\./;
if (full_path.match(pathRE)){
folder_target_path = full_path.replace(/\/[^\/]*$/, '');
} else {
folder_target_path = full_path;
}
This either matches a path that contains . (period to designate file extension start) then remove the file name with full_path.replace(/\/[^\/]*$/, ''); otherwise don't modify the full path.
Thanks to all!
Regards,
Steve