Extract filename and extension in js - javascript

Need a method in JavaScript to extract a filename and extension.
Example:
/vagrant/modules/americabuy/tranzilaNotifications/class/../../../a_tranzila/log/tranzila_2018-01-09_08-58-47.json
returns array: ["tranzila_2018-01-09_08-58-47","json"]

In Node.js
var path = require('path');
function getFilenameAndExtension(pathfilename){
return [path.parse(pathfilename).name, path.parse(pathfilename).ext];
}
In JavaScript
function getFilenameAndExtension(pathfilename){
var filenameextension = pathfilename.replace(/^.*[\\\/]/, '');
var filename = filenameextension.substring(0, filenameextension.lastIndexOf('.'));
var ext = filenameextension.split('.').pop();
return [filename, ext];
}
Result
getFilenameAndExtension("/vagrant/modules/americabuy/tranzilaNotifications/class/../../../a_tranzila/log/tranzila_2018-01-09_08-58-47.json");
//Result -> ["tranzila_2018-01-09_08-58-47", "json"]
It works too if the filename have more than one ".". For example:
getFilenameAndExtension("../log/tranzila.2018-01-09.08-58-47.json");
// Result: ["tranzila.2018-01-09.08-58-47", "json"]

You can use the split() function combined with pop() to get the file full name (name + extension) and detect the separation between your file name and extension with lastIndexOf() :
var str = '/vagrant/modules/americabuy/tranzilaNotifications/class/../../../a_tranzila/log/tranzila_2018-01-09_08-58-47.json';
function fileNameAndExt(str){
var file = str.split('/').pop();
return [file.substr(0,file.lastIndexOf('.')),file.substr(file.lastIndexOf('.')+1,file.length)]
}
console.log(fileNameAndExt(str));

No need to complex Things.
You have a split(" ") method in Javascript that does what you want.
var str = '/vagrant/modules/americabuy/tranzilaNotifications/class/../../../a_tranzila/log/tranzila_2018-01-09_08-58-47.json';
var file = str.split('/').pop();
var fileAndExtensionArray = file.split("."); // This is ["tranzila_2018-01-09_08-58-47","json"]

Short String.prototype.match() solution:
var filepath = '/vagrant/modules/americabuy/tranzilaNotifications/class/../../../a_tranzila/log/tranzila_2018-01-09_08-58-47.json',
result = (m = filepath.match(/([^/]+)\.([^.]+)$/)) && m.slice(1,3);
console.log(result);

var filepath='/vagrant/modules/americabuy/tranzilaNotifications/class/../../../a_tranzila/log/tranzila_2018-01-09_08-58-47.json';
var filename=filepath.split("")[filepath.length-1];
var extension=filename.split(".")[filename.length-1];

Related

Remove sections of url to only keep file name

I want to remove everything in the URL and only keep the name of the file/image. The URL is a dynamic input/variable.
Code:
var str = "http://website.com/sudir/sudir/subdir/Image_01.jpg";
str = str.replace("http://website.com/sudir/sudir/subdir/", "")
.replace(/[^a-z\s]/gi, ' ').replace("_", " ")
.replace("subdir", "").toLowerCase().slice(0,-4);
You can do this easily with lastIndexOf():
var str = "http://website.com/sudir/sudir/subdir/Image_01.jpg";
str.substring(str.lastIndexOf("/") + 1)
//"Image_01.jpg"
This function will give you the file name,
function GetFilename(url)
{
if (url)
{
var m = url.toString().match(/.*\/(.+?)\./);
if (m && m.length > 1)
{
return m[1];
}
}
return "";
}
From How to catch the end filename only from a path with javascript?
var filename = path.replace(/.*\//, '');
From Getting just the filename from a path with Javascript
var fileNameIndex = yourstring.lastIndexOf("/") + 1;
var filename = yourstring.substr(fileNameIndex);
I know you haven't specified the exact URL format and whether this may be possible in your situation, but this may be a solution worth considering.
Javascript
var str = "http://website.com/sudir/sudir/subdir/Image_01.jpg?x=y#abc";
console.log(str.split(/[?#]/)[0].split("/").slice(-1)[0]);
str = "http://website.com/sudir/sudir/subdir/Image_01.jpg";
console.log(str.split(/[?#]/)[0].split("/").slice(-1)[0]);
On jsfiddle
You can always Regex to extract data from strings:
The Regex to extract data from URL:
"http://website.com/sudir/sudir/subdir/(?<FileName>[0-9A-Za-z._]+)"

Insert a string before the extension in a filename

How can I insert a string before the extension in an image filename? For example, I need to convert this:
../Course/Assess/Responsive_Course_1_1.png
to this:
../Course/Assess/Responsive_Course_1_1_large.png
If we assume that an extension is any series of letters, numbers, underscore or dash after the last dot in the file name, then:
filename = filename.replace(/(\.[\w\d_-]+)$/i, '_large$1');
None of the answers works if file doesn't have extension.
Here's a solution that works for all cases.
function appendToFilename(filename, string){
var dotIndex = filename.lastIndexOf(".");
if (dotIndex == -1) return filename + string;
else return filename.substring(0, dotIndex) + string + filename.substring(dotIndex);
}
Use javascript lastIndexOf, something like:
var s = "Courses/Assess/Responsive_Cousre_1_1.png";
var new_string = s.substring(0, s.lastIndexOf(".")) + "_large" + s.substring(s.lastIndexOf("."));
var s = '../Course/Assess/Responsive_Course_1_1.png'
s.replace(/\.png$/, '_large.png');
This will do the job. By the way, it's night here. :)
UPDATE:
A more general way would be this:
var s = '../Course/Assess/Responsive_Course_1_1.png';
s.replace(/(\.[^\.]+)$/, '_large$1');
Either $1 match a filename with no extension or $2 match an extension.
filename = filename.replace(/^([^.]+)$|(\.[^.]+)$/i, '$1' + "_large" + '$2');
for files without extension and files includes extension. thanks #paul !
filename = filename.replace(/^([^.]+)$|(\.[^.]+)$/i, '$1' + "-thumb" + '$2');
If you are not sure what could be the incoming file's extension then this helps:
function renameFileA(imgUrl) {
var extension = `.${imgUrl.split('.').pop()}`
var [fileName] = imgUrl.split(extension);
return `${fileName}_large${extension}`;
};
// this is clean but I don't understand what's going on till I do research ;)
function renameFileB(imgUrl) {
return imgUrl.replace(/(\.[\w\d_-]+)$/i, '_large$1');
};
var valA = renameFileA('http//www.app.com/img/thumbnails/vid-th.png');
var valB = renameFileB('http//www.app.com/img/thumbnails/vid-th.jpg');
console.log('valA', valA);
console.log('valB', valB);
Simple regex replace
filename = filename.replace(/(\.[^.]+)$/i, '_large$1')
Just in case: Flexible to change pattern like prefix or suffix
const url = 'https://example.com/path/filename.png?a&b=c'
const regex = /((?:.+\/.+)+\/)(.?.+)+\.(.+)/
const result1 = url.replace(regex,'$1prefix_$2.$3')
const result2 = url.replace(regex,'$1$2_suffix.$3')
const result3 = '../Course/Assess/Responsive_Course_1_1.png'.replace(regex,'$1$2_large.$3')
const result4 = '../path/file'.replace(/(\/)(.?.+)/,'$1$2_suffix')
console.log(result1) // https://example.com/path/prefix_filename.png?a&b=c
console.log(result2) // https://example.com/path/filename_suffix.png?a&b=c
console.log(result3) // ../Course/Assess/Responsive_Course_1_1_large.png
console.log(result4) // ../path/file_suffix
Credit: Regex from: https://stackoverflow.com/a/60538390/622813

How to get an image name using jQuery?

Let's says I have :
<img src='static/images/banner/blue.jpg' />
Using jQuery, how could I get the blue data ?
If I use $('img').attr('src'), I can get the whole URI. In that case, what is the best way to remove the extension and all the path ?
There are a couple gotcha here- local files may use the other slash ('\') in the pathname, and some filenames can have hash or search tails defined, or not have an extension.
String.prototype.filename=function(extension){
var s= this.replace(/\\/g, '/');
s= s.substring(s.lastIndexOf('/')+ 1);
return extension? s.replace(/[?#].+$/, ''): s.split('.')[0];
}
console.log($('img').attr('src').filename());
var src = $('img').attr('src').split('/');
var file = src[src.length - 1];
Should work
Just split the string:
var src = $('img').attr('src'); // "static/images/banner/blue.jpg"
var tarr = src.split('/'); // ["static","images","banner","blue.jpg"]
var file = tarr[tarr.length-1]; // "blue.jpg"
var data = file.split('.')[0]; // "blue"
Regex will be your best friend here...
var filename = fullUri.replace( /^.*?([^\/]+)\..+?$/, '$1' );
Say we have:
<img src="path/to/awesome/image/foobar.jpg" />
Here's what we do to extract the file name:
Array.prototype.filename = function() {
var tmp = this.split('/');
return tmp[tmp.length-1].match(/(.*)\.[\w]+$/)[1];
});
$('img').attr('src').filename();
Result:
console.log(name); // foobar
src = $('img').attr('src');
src_array = src.split('/');
src = src_array[src.length-1];
var src= $('img').attr('src');
var name = src.match(/static\/images\/banner\/(.*)\.jpg/)[1];

From full path to file, to only displaying filename

How can I convert a full path
C:\some folder\another folder\my-picture.jpg
To:
my-picture.jpg
??
Thank you in advance.
You can read from the final \ (also works for bare "file.ext");
var fn = "C:\\some folder\\another folder\\my-picture.jpg";
alert( fn.substr(fn.lastIndexOf("\\") + 1) );
var str = "C:\\some folder\\another folder\\my-picture.jpg";
var fileName = str.split("\\").pop();
if you need to handle different OS file paths
var str = "C:\\some folder\\another folder\\my-picture.jpg";
var fileName = str.split(/[\\\/]/).pop();

Replace filename using JavaScript?

Can someone show me how to do the following in JavaScript? I know how to grab the src of the image, I just want to be able to replace the filename with something new.
/image/any/path/ANY-TEXT_HERE.png
/image/any/path/NEWTEXT.png
Case-insensitive version:
path = path.replace(/(.*)\/.*(\.png$)/i, '$1/NEWTEXT$2')
Remove the i after / to make it case-sensitive.
Another option:
var filename = "/image/any/path/NEWTEXT.png";
var splitFilename = filename.split("/");
var newPath = splitFilename.slice(0, splitFilename.length - 1).join("/")
if (newPath.length !== 0) {
newPath += "/"
}
newPath += newFilename;
All the other solutions so far assume there actually IS a path. They work only if there is at least one forward slash. This tested functions works in all cases including an empty path:
function rename_img_file(text, newname)
{ // Rename file in a IMG src (no query or fragment)
var re = /^(.*\/)?[^\/]+\.(png|gif|jpe?g)$/i;
var rep_str = '$1' + newname + '.$2';
text = text.replace(re, rep_str);
return text;
}
var url = "/image/any/path/ANY-TEXT_HERE.png";
var mystring = "NEWTEXT";
var ind1 = url .lastIndexOf('/');
var ind2 = url .lastIndexOf('.');
var new_url = url.substring(0,ind1+1 )+ mystring + url.substring(ind2 );
alert(new_url );
javascript its really restrictive to files.
I assume that you want to do that on a server. if that so, you should use a serverside script, not a client side.
Maybe you ar talking about an ajax script
if you can explain a ltl further maybe i can lendyou a hand

Categories

Resources