Grunt Task - Get Filename from path without extension - javascript

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

Related

Convert path string from unc to uri, replacing slashes with backslashes in Google Apps Script

I need to convert a path this UNC. I have searched and search and cannot piece anything together.
"\\NAS_01\GlobalShare\Docs\Customers\2017\S\Smith, John\photo1.jpg"
I need to remove the "\NAS_01\GlobalShare\Docs\Customers\" portion of the path and also "photo1.jpg" and end up with:
2017\S\Smith, John\
so that I can pass it to the following function:
function getDriveFolderNoCreate(path, rootFolder) {
var name, folder, search, fullpath;
// Remove extra slashes and trim the path
fullpath = path.replace(/^\/*|\/*$/g, '').replace(/^\s*|\s*$/g, '').split("/");
// Always start with the main Drive folder
folder = rootFolder;
for (var subfolder in fullpath) {
name = fullpath[subfolder];
search = folder.getFoldersByName(name);
if (search.hasNext()) {
var folder = search.next;
var folderID = folder.getId();
return folderID;
}
}
}
My intention is to return a url to open the Google Drive folder with the same path.
I ended up with a multi-part solution that works very well.
I paste the fill UNC path to cell B2.
This formula is in B3 =Index(split(B2, "\"), 0, 8)
It returns the exact folder name i need.
Then in my gs file:
function findDriveFolder() {
var pFId = "XYZ1233333333333";
var input = SpreadsheetApp.getActive().getRange("B3").getValue();
var folders = DriveApp.getFoldersByName(input);
Logger.log("folders: " + folders[0]);
while (folders.hasNext()) {
var folder = folders.next();
var url = folder.getUrl();
showAnchor("View Folder", url);
}
}
function showAnchor(name,url) {
var html = '<html><body>'+name+'</body></html>';
var ui = HtmlService.createHtmlOutput(html)
SpreadsheetApp.getUi().showModelessDialog(ui,"Files Folder");
}
I have not implemented the searchFolders part yet that I hope will speed it up. At least it's working for now.
Apps Script needs your input backslashes to be escaped if you are writing the string yourself (i.e. testing input).
wrong:
input = "\\NAS_01\GlobalShare\Docs\Customers\2017\S\Smith, John\photo1.jpg"
right:
input = "\\\\NAS_01\\GlobalShare\\Docs\\Customers\\2017\\S\\Smith, John\\photos1.jpg"
In Apps Script then, I am able to get the matching portion with the following regex:
/\d{4}\\[A-Z]\\.+\\/
i.e:
function unc2uri(input) {
const forwardSlash = String.fromCharCode(47);
const backSlash = String.fromCharCode(92);
if(!input)
input = '\\\\NAS_01\\GlobalShare\\Docs\\Customers\\2017\\S\\Smith, John\\photo1.jpg';
// Should show \\NAS_01\GlobalShare\Docs\Customers\2017\S\Smith, John\photo1.jpg
Logger.log(input);
const matcher = /\d{4}\\[A-Z]\\.+\\/;
const arrayOfMatches = input.match(matcher);
// Should show [2017\S\Smith, John\].
Logger.log(arrayOfMatches);
}
To verify, ask for the input string from someplace else (example, Browser.inputBox) and pass that to the above as input:
function readInput() {
unc2uri(Browser.inputBox("What's the path?"));
}
In the inputBox, you would enter the string you expect to be sent, as we view it, i.e. \\NAS_01\GlobalShare\Docs\Customers\2017\S\Smith, John\photo1.jpg

How do I get rid of everything, every string before a specified word in jquery?

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

How to get a specific portion of the url using javascript?

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));
})()

Removing the last character from file stream in node.js (fs module)

Using node.js, I am trying to build an array of objects and write them to a file. To do this, I'm using the built in fs library.
After calling
var file = fs.createWriteStream('arrayOfObjects.json'); and file.write('[') I run several asynchronous functions to eventually append objects like this:
file.write(JSON.stringify(objectToAppend) + ',\n')
I can determine when all of the objects have stopped appending, and this is where I run file.write(']') and file.end(). My problem is that adding the last comma to the end of the last object causes the JSON to be invalid.
It is very difficult to determine where and when the last object is being created due to the asynchronous nature of the script, so I was wondering if there is a way to strip or remove characters from a file-stream. If so, I could do this before adding the last ']' character.
I could do this manually, but I was hoping to pipe this to another application. The only solution I've thought about is using the fs.truncate() function, however this doesn't seem to work for file streams, and neither file.length or file.length() will give me the length of the contents because it is not a string so it's difficult to determine how or where to truncate the file.
For now I have just been adding '{}]' to the end of the array to make it valid JSON, but this empty object may cause some problems later.
Also note: the array of objects I am writing in this stream is VERY large, so I would rather not end the stream and re-open the file.
I'd recommend to prepend the separator instead, so that you dynamically can adjust it after the first call:
file.write('[\n')
var sep = "";
forEach(function(objectToAppen) {
file.write(sep + JSON.stringify(objectToAppend))
if (!sep)
sep = ",\n";
});
Example using JSONStream:
var JSONStream = require('JSONStream');
var fs = require('fs');
var jsonwriter = JSONStream.stringify();
var file = fs.createWriteStream('arrayOfObjects.json');
// Pipe the JSON data to the file.
jsonwriter.pipe(file);
// Write your objects to the JSON stream.
jsonwriter.write({ foo : 'bar#1' });
jsonwriter.write({ foo : 'bar#2' });
jsonwriter.write({ foo : 'bar#3' });
jsonwriter.write({ foo : 'bar#4' });
// When you're done, end it.
jsonwriter.end();
Here's a snippet incorporating robertklep's answer. This converts from a pipe-separated file to json:
var fs = require('fs');
var readline = require('readline');
var JSONStream = require('JSONStream');
// Make sure we got a filename on the command line.
if (process.argv.length < 3) {
console.log('Usage: node ' + process.argv[1] + ' FILENAME');
process.exit(1);
}
var filename = process.argv[2];
var outputFilename = filename + '.json';
console.log("Converting psv to json. Please wait.");
var jsonwriter = JSONStream.stringify();
var outputFile = fs.createWriteStream(outputFilename);
jsonwriter.pipe(outputFile);
var rl = readline.createInterface({
input: fs.createReadStream(filename),
terminal: false
}).on('line', function(line) {
console.log('Line: ' + line);
if(!/ADDRESS_DETAIL_PID/.test(line))
{
var split = line.split('|');
var line_as_json = { "address_detail_pid": split[0], "flat_type": split[1], "flat_number": split[2], "level_type": split[3], "level_number": split[4], "number_first": split[5], "street_name": split[6], "street_type_code": split[7], "locality_name": split[8], "state_abbreviation": split[9], "postcode": split[10], "longitude": split[11], "latitude": split[12] };
jsonwriter.write(line_as_json);
}
}).on('close', () => {
jsonwriter.end();
});;
console.log('psv2json complete.');
The accepted answer is interesting (prepending the separator) but in my case I have found it easier to append the separator and remove the last character of the file, just as suggested in the question.
This is how you remove the last character of a file with Node.js :
import fs from 'fs'
async function removeLastCharacter(filename) {
const stat = await fs.promises.stat(filename)
const fileSize = stat.size
await fs.promises.truncate(filename, fileSize - 1)
}
explanation :
fs.promises.stat gives us some information about the file, we will use its size.
fs.promises.truncate remove from the file what is after a certain position
We use the position fileSize - 1 which is the last character.
Note :
Yes I know that we need to wait until the stream is closed, but this is ok because truncate and stat functions are very fast and doesn't depend on the file size, it doesn't have to read its content.

How can I get the current directory name in Javascript?

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

Categories