How to get an image name using jQuery? - javascript

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

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

How to get the last two characters of url with jQuery?

I have a url with the following format:
base/list.html?12
and I want to create a variable which will be equal to the digits after the question mark in the url of the page. Something like:
var xxx = anything after the ? ;
Then I need to load dynamic data into that page using this function:
if(document.URL.indexOf(xxx) >= 0){
alert('Data loaded!');
}
How can I achieve this? and are the codes above correct?
Thanks
You can use split to get the characters after ? in the url
var xxx = 'base/list.html?12';
var res = xxx.split('?')[1];
or for current page url
var res = document.location.href.split('?')[1];
res = document.location.href.split('?')[1];
Duplicate of 6644654.
function parseUrl( url ) {
var a = document.createElement('a');
a.href = url;
return a;
}
var search = parseUrl('base/list.html?12').search;
var searchText = search.substr( 1 ); // removes the leading '?'
document.location.search.substr(1) would also work

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]

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