I have a next string like:
<img src="../uplolad/commission/ranks/avatar.jpg' . $row[$c_name] .'" width="50" height="50"/>
How can i get a image file name in javascript? I know only PHP regexes. Extention of a file can be different.
The result must be: avatar.jpg
Regex is not ideal for this. JavaScript can traverse the HTML as distinct objects more readily than as a long string. If you can identify the picture by anything, say by adding an ID to it, or an ID to a parent with that as the only image, you'll be able to access the image from script:
var myImage = document.getElementById('imgAvatar'); // or whatever means of access
var src = myImage.src; // will contain the full path
if(src.indexOf('/') >= 0) {
src = src.substring(src.lastIndexOf('/')+1);
}
alert(src);
And if you want to edit, you can do that just as well
myImage.src = src.replace('.jpg', '.gif');
Fetch it following coding which can help what you want to get.
<script type="text/javascript">
function getImageName(imagePath) {
var objImage = new RegExp(/([^\/\\]+)$/);
var getImgName = objImage.exec(imagePath);
if (getImgName == null) {
return null;
}
else {
return getImgName[0];
}
}
</script>
<script>
var mystring = getImageName("http://www.mypapge.mm/myimage.png")
alert(mystring)
</script>
Here's a shorter variation of David Hedlund's answer that does use regex:
var myImage = document.getElementById('imgAvatar'); // or whatever means of access
alert(myImage.src.replace( /^.+\// , '' ));
Related
I'm wondering how to extract images from RSS and Atom feeds so I can use them as a thumbnail when display the feed in a container with it's relative Title, Description and Link. So far my code, (shown below), grabs images from only certain feed types, I'm wondering how I can grab every image my script comes across.
if (feed_image_type == "description") {
item_img = $($(this).find('description').text()).find("img").attr("src");
} else if (feed_image_type == "encoded") {
item_img = $($(this).find('encoded').text()).find("img").attr("src");
} else if (feed_image_type == "thumbnail") {
item_img = $(this).find('thumbnail').attr('url');
} else {
item_img = $(this).find('enclosure').attr('url');
}
For example, I cannot figure out how I would grab the image link from the code rss feed snippet below:
<description>
<![CDATA[
<img src="https://i.kinja-img.com/gawker-media/image/upload/s--E93LuLOd--/c_fit,fl_progressive,q_80,w_636/hd6cujrvf1d72sbxsbnr.jpg" /><p>With a surprise showing of skill and, at one point, a miracle, the bottom-ranked team in the European <em>League </em>Championship Series will not end the summer winless.<br></p><p>Read more...</p>
]]>
</description>
Using these sources:
parse html inside cdata using jquery or javascript
jQuery.parseXML
https://www.w3schools.com/xml/dom_cdatasection.asp
It is essential that you get your content correctly as XML, by setting the dataType to 'xml'.
This code is self-contained and works:
var xmlString = '<Customer><![CDATA[ <img src="y1" /> ]]></Customer>';
var xmlObj = $.parseXML(xmlString);
var cdataText = xmlObj.firstChild.firstChild.textContent;
var jqueryObj = $(cdataText);
var imgUrl = jqueryObj.find('img').attr('src');
console.log(imgUrl);
This is slightly imprecise because you don't give quite enough information to exactly reproduce your situation. I will start as though this from your question is the only part of your code:
if (feed_image_type == "description") {
item_img = $($(this).find('description').text()).find("img").attr("src");
}
This ought to get close:
if (feed_image_type == "description") {
var cdataText = $(this).firstChild.firstChild.textContent;
var jqueryObj = $(cdataText);
item_img = jqueryObj.find('img').attr('src');
}
You can also try this.
let str = `<description>
<![CDATA[
<img src="https://i.kinja-img.com/gawker-media/image/upload/s--E93LuLOd--/c_fit,fl_progressive,q_80,w_636/hd6cujrvf1d72sbxsbnr.jpg" /><p>With a surprise showing of skill and, at one point, a miracle, the bottom-ranked team in the European <em>League </em>Championship Series will not end the summer winless.<br></p><p>Read more...</p>
]]>
</description>`;
//We need to strip CDATA in our case. Otherwise the parser will not parse the contents inside it.
str = str.replace("<![CDATA[", "").replace("]]>", "")
let parser = new DOMParser();
let xmlDoc = parser.parseFromString(str,"text/xml");
let images = [...xmlDoc.querySelectorAll('img')].map(image=>image.getAttribute('src'))
How can I pick up image name in html using JavaScript? I searched google and there are some documents about how to get image name on <img> tag,
var filename = tag.replace( /^.*?([^\/]+)\..+?$/, '$1' );
But it return just one name of images. What I'm going to do is get all images name. Imagine the html below,
<html>
<body>
<div class="imagebox">
<img src="/some/path/imageOne.jpg">
<img src="/some/path/imageTwo.jpg">
<img src="/some/path/imageThree.jpg">
</div>
</body>
</html>
after magic, return
imageOne, imageTwo, imageThree. How can I do this..?
Add the following Javascript code at the bottom of your html page :
Solution for browser environment :
var images = document.getElementsByTagName('img');
var images_urls = [];
var images_names = [];
var tmp;
for(var i=0;i < images.length;i++){
images_urls[i] = images[i].getAttribute('src');
tmp = images[i].getAttribute('src').split('/');
images_names[i] = tmp[tmp.length -1].split['.'][0];
}
console.log(images_names); // ["imageOne", "imageTwo", "imageThree"]
and now images_names is an array containing the image names, in this case imageOne,imageTwo and imageThree
Solution for Node.js environment:
lets say you have images url stored in images variable like this :
var images = ["/some/path/imageOne.jpg", "/some/path/imageTwo.jpg", "/some/path/imageThree.jpg"];
you can use Regex, but in this case you can do it easily without using Regex, just split each image url and grab the last part of it, pretty simple, something like this :
var images_names = [];
var tmp
for(var i=0;i < images.length;i++){
tmp = images[i].split('/');
images_names[i] = tmp[tmp.length -1].split['.'][0];
}
console.log(images_names); // ["imageOne", "imageTwo", "imageThree"]
It is the same solution for both Browser and Node.js environment except for the way you get the elements.
Hope this helps.
I want to access the Javascript variable value outside the Javascript tag.
function getprices(input) {
return input.match(/[0-9]+/g);
}
var subtotals = get_getprices('%GLOBAL_OrderTotal%');
var Grand_total = subtotals[0];
<img height="0" width="0" border="0" src="http://testing.com?merchantId=M1&orderNo=%%GLOBAL_OrderId%%&saleAmount=I want the Grand+Total Value here">
You'd need to update the src property on that img element. Let's suppose you gave the img an id (you don't have to, there are other ways to select it, but I'm keeping it simple):
<img id="the-image" height="0" width="0" border="0" src="http://testing.com?merchantId=M1&orderNo=%%GLOBAL_OrderId%%&saleAmount=I want the Grand+Total Value here">
Then:
function getprices(input) {
return input.match(/[0-9]+/g);
}
var subtotals = getprices('%%GLOBAL_OrderTotal%%'); // <=== Changed to `getprices`, was `get_getprices`
var Grand_total=subtotals[0];
var img = document.getElementById("the-image");
img.src = "http://testing.com?merchantId=M1&orderNo=%%GLOBAL_OrderId%%&saleAmount=" + Grand_total;
It looks like Grand_total will always be a number, but for the general case where it might not be, , be sure to use encodeURIComponent (it doesn't do any harm even if it is a number):
img.src = "http://testing.com?merchantId=M1&orderNo=%%GLOBAL_OrderId%%&saleAmount=" + encodeURIComponent(Grand_total);
If you didn't use an id on the img, that's fine, you can use any CSS selector via document.querySelector. That's supported by all modern browsers, and also IE8.
Note that there are other issues with that code, though, not least that getprices looks fairly suspect.
All you need to do is to assign your value to src of img in your javascript
$("#imgNeeded").attr("src",".../"+Globalvalue)
As T.J. Crowder said. make sure you encode URI if your variable contain something other than number
You can use
document.getElementsByTagName("img")[***index of the image tag***].src = "<THE STRING>"+<THE VARIABLE>+"<THE REMAINING STRING>";
or assign an id to the <img> and use
`document.getElementById("id of the image").src = ""++"";
The problem the provided approaches share is, that how they are, your image will get loaded with the unwanted source before changed:
<html>
<head>
<script>
function getprices(input){return input.match(/[0-9]+/g)};
function changeSrc(){
var tE = document.querySelector("img[src*='saleAmount=']");
var tS = getprices('anyPrice1');
if (tE && tS) tE.src += encodeURIComponent(tS[0]);
};
</script>
</head>
<body onload = 'changeSrc()'>
<img height = '0' width = '0' border = '0' src = 'http://JUSTTOSHOWtesting.com?merchantId=M1&orderNo=%%GLOBAL_OrderId%%&saleAmount=' onerror = 'console.log(this.src)'>
</body>
Your console will log two calls:
- GET http://justtoshowtesting.com/?merchantId=M1&orderNo=%%GLOBAL_OrderId%%&saleAmount= net::ERR_NAME_NOT_RESOLVED
- GET http://justtoshowtesting.com/?merchantId=M1&orderNo=%%GLOBAL_OrderId%%&saleAmount=1 net::ERR_NAME_NOT_RESOLVED
So what you could do is placing a placeholder, until you have the source you need:
<html>
<head>
<script>
function getprices(input){return input.match(/[0-9]+/g)};
function createSrc(){
var tE = document.querySelector("ins[src*='saleAmount=']");
var tS = getprices('anyPrice1');
if (tE && tS){
var tI = document.getElementById('iPlaceholder');
if (!tI){
tI = document.createElement('img');
tI.id = 'iPlaceholder';
tI.onerror = function(){console.log(this.src)};
tE.parentNode.insertBefore(tI, tE.nextSibling);
};
tI.src = tE.getAttribute('src') + encodeURIComponent(tS[0]);
};
};
</script>
</head>
<body onload = 'createSrc()'>
<ins src = 'http://JUSTTOSHOWtesting.com?merchantId=M1&orderNo=%%GLOBAL_OrderId%%&saleAmount='></ins>
</body>
</html>
Now your console will merely log one call:
- GET http://justtoshowtesting.com/?merchantId=M1&orderNo=%%GLOBAL_OrderId%%&saleAmount=1 net::ERR_NAME_NOT_RESOLVED
My Random Number Generate code is
var randomnumber=Math.floor(Math.random()*99999)
Now I want to put this variable output in a image scr url..
Here is my url
<img src="http://www.myexample.com/get/image.php?vcid=14851&t=481" alt="" id="imge"/>
So what will my code?
<img src="http://www.myexample.com/get/image.php?vcid='+ randomnumber +'&t=481" alt="" id="imge"/>
??
Please help me
In pure Javascript you could do it like
var randomNumber = 1;
var image = document.getElementById("imageId");
var imageSrc = image.getAttribute("src");
image.setAttribute("src", imageSrc + randomNumber);
To put your number at the correct place you could use some string split functions, but since the order of query strings don't matter you should just put your vcid query at the end.
Try adding this in your <script>:
document.getElementById("imge").src = "http://www.myexample.com/get/image.php?vcid=" + randomnumber + "&t=481";
I'd personally suggest:
var img = document.getElementById('imge');
img.src = img.src.replace(/vcid=(\d+)/, function(){
return randomnumber=Math.floor(Math.random()*99999);
});
// purely to see the src has been changed, this is *not* relevant or required
img.title = img.src;
<img src="http://www.myexample.com/get/image.php?vcid=14851&t=481" alt="" id="imge"/>
References:
JavaScript Regular Expressions.
String.replace().
I have to display images to the browser and I want to get the image from a JSON response and display it to the browser using Javascript. This is what the JSON response looks like:
[{
"0":"101",
"member_id":"101",
"1":"3k.png",
"image_nm":"3k.png",
"2":"\/images\/phones\/",
"image_path":"\/images\/"
},{
"0":"102",
"member_id":"102",
"1":"mirchi.png",
"image_nm":"mirchi.png",
"2":"images\/phones\/",
"image_path":"images\/phones\/"
},{
"0":"103",
"member_id":"103",
"1":"masti.png",
"image_nm":"masti.png",
"2":"images\/phones\/",
"image_path":"images\/phones\/"
}]
How do I do this (I am a beginner)?
here is the code what i wrote...
var jsonString = '[{"0":"101","member_id":"101","1":"3k.png","image_nm":"3k.png","2":"\/images\/phones\/","image_path":"\/images\/phones\/"},{"0":"102","member_id":"102","1":"mirchi.png","image_nm":"mirchi.png","2":"images\/phones\/","image_path":"images\/phones\/"},{"0":"103","member_id":"103","1":"masti.png","image_nm":"masti.png","2":"images\/phones\/","image_path":"images\/phones\/"}]';
var obj = JSON.parse(jsonString);
for(var i = 0, len = obj.length; i < len; i++){
var img = new Image();
img.setAttribute("src",obj[i][2] + obj[i][1]);
document.body.appendChild(img);
}
Assuming you parsed your json in a variable called json, this would add all images in a container with id yourcontainer:
var images = '';
for( var i=0, max<json.length; ++i ) {
images += '<img src="' + json[i]['image_path'] + json[i]['image_nm'] + '" />';
}
document.getElementById( 'yourcontainer' ).innerHTML = images;
Seems pretty straight forward. If this is json_encoded, then we can use json[key] to get the value, if you aren't familiar with the term 'key', json encodes arrays in the key:value, format, so for this, if we used json[member_id], we would get '101', if we used json[image_nm], we would get '3k.png', putting this all together it seems as if it's pretty well separated, you just have to know what goes where. I have an idea, but not 100%,I would expect you to do something like
var myImages = '';
for(var i = 0; i < json.length; i++){
myImages += '<img src="'+json[i]['image_path']+json[i]['img_nm']+'" />';
}
document.getElementById('myImgHolder').innerHTML = myImages;
Based on your json data, this would evaluate a variable and test it against the length of the json array. The statement also declares that while the variable is less than the total length of the json array, we will iterate to the next object. We would expect output along the format of -
<img src="/images/3k.png" />.
Then it would take the new images and place them in a Div with the id of myImgHolder.
Hope this helps.
EDIT 1
If you don't have a container to place these images inside of it, then you will need to create the container and place it somewhere.
var myImgHolder = document.createElement('div');
myImgHolder.setAttribute("id", "myImgHolder");
document.getElementById('ICanTargetThis').appendChild(myImgHolder);
The above code sets the variable myImgHolder to the creation of a new DIV element. Then, using the variable, we declare the attribute "id" to set as 'myImgHolder'. Now we have the element. But what do we do with it? Well we MUST target an existing element within our page, even if we're just targeting the tag...something. then we use the .appendChild method and use our variable...appendChild(myImgHolder);
You can use jQuery here.
Add following script in the head tag.
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script>
$(document).ready(function () {
var url = "entries.json";
$.getJSON(url, function (url){
var img= "";
$.each(url, function () {
img += '<li><img src= "' + this.images+ '"></li>';
});
$('body').append(img);
});
});
</script>