Insert a string before the extension in a filename - javascript

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

Related

Extract filename and extension in js

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];

replace a string partially with something else

lets say I have this image address like
https://firebasestorage.googleapis.com/v0/b/myproj-d.appspot.com/o/FILE_NAME.jpg?alt=media&token=124bb2bf-c6ef-432b-92c7-7032563ba31b
how is it possible to replace FILE_NAME.jpg with THUMB_FILE_NAME.jpg
Note: FILE_NAME and THUMB_FILE_NAME are not static and fix.
the FILE_NAME is not fixed and I can't use string.replace method.
eventually I don't know the File_Name
Use replace
.replace(/(?<=\/)[^\/]*(?=(.jpg))/g, "THUMB_FILE_NAME")
or if you want to support multiple formats
.replace(/(?<=\/)[^\/]*(?=(.(jpg|png|jpeg)))/g, "THUMB_FILE_NAME")
Demo
var output = "https://firebasestorage.googleapis.com/v0/b/myproj-d.appspot.com/o/FILE_NAME.jpg?alt=media&token=124bb2bf-c6ef-432b-92c7-7032563ba31b".replace(/(?<=\/)[^\/]*(?=(.jpg))/g, "THUMB_FILE_NAME");
console.log( output );
Explanation
(?<=\/) matches / but doesn't remember the match
[^\/]* matches till you find next /
(?=(.jpg) ensures that match ends with .jpg
To match the FILE_NAME, use
.match(/(?<=\/)[^\/]*(?=(.(jpg|png|jpeg)))/g)
var pattern = /[\w-]+\.(jpg|png|txt)/
var c = 'https://firebasestorage.googleapis.com/v0/b/myproj-d.appspot.com/o/FILE_NAME.jpg?alt=media&token=124bb2bf-c6ef-432b-92c7-7032563ba31b
'
c.replace(pattern, 'YOUR_FILE_NAME.jpg')
you can add any format in the pipe operator
You can use the String's replace method.
var a = "https://firebasestorage.googleapis.com/v0/b/myproj-d.appspot.com/o/FILE_NAME.jpg?alt=media&token=124bb2bf-c6ef-432b-92c7-7032563ba31b";
a = a.replace('FILE_NAME', 'THUMB_FILE_NAME');
If you know the format, you can use the split and join to replace the FILE_NAME.
let str = "https://firebasestorage.googleapis.com/v0/b/myproj-d.appspot.com/o/FILE_NAME.jpg?alt=media&token=124bb2bf-c6ef-432b-92c7-7032563ba31b";
let str_pieces = str.split('/');
let str_last = str_pieces[str_pieces.length - 1];
let str_last_pieces = str_last.split('?');
str_last_pieces[0] = 'THUMB_' + str_last_pieces[0];
str_last = str_last_pieces.join('?');
str_pieces[str_pieces.length - 1] = str_last;
str = str_pieces.join('/');

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._]+)"

Validating url with http:www as optional using regex

I am trying to validate a url where the "http:www" is optional, so the yahoo.com and http://www.yahoo.com needs to be valid url but using the following regex does not take utl3 to be valid one .
How can I fix this ??
function checkUrlTest(url){
var urlregex = new RegExp("^(https?:\/\/www\.)?(^(https?:\/\/www\.)[0-9A-Za-z]+\.+[a-z]{2,5})");
return urlregex.test(url);
}
url3 = "yahoo.com";
url4 = "www.yahoo.com";
alert(checkUrlTest(url3));
(http://)?(www\.)?[A-Za-z0-9]+\.[a-z]{2,3}
In this regex, http://www.yahoo.com, http://yahoo.com and www.yahoo.com are all valid URLs
Just check it out. All problems will resolve.
var rgx = /^\s*(http\:\/\/)?([a-z\d\-]{1,63}\.)*[a-z\d\-]{1,255}\.[a-z]{2,6}\s*$/;
Working Demo http://jsfiddle.net/fy66p/
Solution reside here: Negative Lookahead: http://www.regular-expressions.info/lookaround.html#lookahead with the www case and you should get what you are looking for. Lemme know how it goes!
Hope it fits your needs :)
code
function checkUrlTest(url){
// Try this
var urlregex = new RegExp("^(?!www | www\.)[A-Za-z0-9_-]+\.+[A-Za-z0-9.\/%&=\?_:;-]+$")
return urlregex.test(url);
}
url3 = "yahoo.com";
url4 = "www.yahoo.com";
alert('===> ' + checkUrlTest(url4) + '===> ' + checkUrlTest(url3));
function validateUrl(value)
{
var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*#)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%#!\-\/]))?/
return regexp.test(value);
}
if not try this:
(?i)\b((?:(?:[a-z][\w-]+:)?(?:/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))

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