Replace filename using JavaScript? - 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

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

FileName from url excluding querystring

I have a url :
http://www.xyz.com/a/test.jsp?a=b&c=d
How do I get test.jsp of it ?
This should do it:
var path = document.location.pathname,
file = path.substr(path.lastIndexOf('/'));
Reference: document.location, substr, lastIndexOf
I wont just show you the answer, but I'll give you direction to it. First... strip out everything after the "?" by using a string utility and location.href.status (that will give you the querystring). Then what you will be left with will be the URL; get everything after the last "/" (hint: lastindexof).
Use a regular expression.
var urlVal = 'http://www.xyz.com/a/test.jsp?a=b&c=d';
var result = /a\/(.*)\?/.exec(urlVal)[1]
the regex returns an array, use [1] to get the test.jsp
This method does not depend on pathname:
<script>
var url = 'http://www.xyz.com/a/test.jsp?a=b&c=d';
var file_with_parameters = url.substr(url.lastIndexOf('/') + 1);
var file = file_with_parameters.substr(0, file_with_parameters.lastIndexOf('?'));
// file now contains "test.jsp"
</script>
var your_link = "http://www.xyz.com/a/test.jsp?a=b&c=d";
// strip the query from the link
your_link = your_link.split("?");
your_link = your_link[0];
// get the the test.jsp or whatever is there
var the_part_you_want = your_link.substring(your_link.lastIndexOf("/")+1);
Try this:
/\/([^/]+)$/.exec(window.location.pathname)[1]

Categories

Resources