I have a string like this
var string = '<img src="test.jpg'><img src="test2.jpg>';
var dom = new JSDOM(string,{ includeNodeLocations: true });
dom = dom.window.document.querySelectorAll("img");
for(var i = 0;i< dom.length;i++) {
text = string.replace(/<img[^>]*>/g,'<amp-img layout="responsive" class="ampimageheight" src="'+dom[i].getAttribute('src')+'" width="200" height= "100"></amp-img>');
}
But my output is
<amp-img layout="responsive" class="ampimageheight" src="test2.jpg" width="200" height= "100"></amp-img><amp-img layout="responsive" class="ampimageheight" src="test2.jpg" width="200" height= "100"></amp-img>
In which only the second image src is replaced for 2 imags.I think this is because of the asynchronous.Can anyone please help me.Thanks.
Well, if you run replace in a loop, you don't need set the Regex's flag.
Because that replace all img when first time loop.
After first loop is do nothing.
So, you can remove Regex flag, or use a callback replace your function's second arguments, like this.
text = string.replace(/<img[^>]*>/g, function(str, index){
return '<amp-img layout="responsive" class="ampimageheight" src="'+dom[index].getAttribute('src')+'" width="200" height= "100"></amp-img>'
});
And it doesn't need loop;
Related
This question already has answers here:
jquery's append not working with svg element?
(17 answers)
Closed 2 years ago.
I'm trying to use JQuery to create an SVG element. The contents of the SVG is generated from a list of strings which is where I'm having my issues.
I'm populating a variable called 'arr' by looping through several hundred items in my database and creating an svg rect shaped based on that data which then gets appended to 'arr'. How can i append this list of string elements to my main SVG element in order to properly display it?
The main points here are:
Arr is populated with a list of strings, each one representing a shape to go inside the svg
The final Arr will be several hundreds strings
var mapSvg = $.parseHTML('<svg id="tile-map-svg" width="100%" height="300"></svg>');
arr = [
'<rect height="50" width="50" fill="blue"/>',
'<rect height="20" width="20" fill="green"/>'
]
mapSvg[0].append(arr);
$('#tile-map').append(mapSvg);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<div style="background:lightblue; padding:10px;">
<div id="tile-map">
</div>
<svg id='tile-map-svg' width="100" height="100">
<rect height="25" width="25" fill="red" class="tile"/>
</svg>
</div>
I also tried this and it didn't work either...
var mapSvg = $.parseHTML('<svg id="tile-map-svg" width="100%" height="600"></svg>');
arr = [
'<rect height="50" width="50" fill="blue"/>',
'<rect height="20" width="20" fill="green"/>'
]
for (var i = 0; i < arr.length; i++) {
var el = $.parseHTML(arr[i])[0];
mapSvg[0].append(el);
}
$('#tile-map').append(mapSvg);
How about looping over all the elements in arr before parsing the html:
let html = '<svg id="tile-map-svg" width="100%" height="300">';
arr.forEach(shape => {
html += shape;
});
html += "</svg>";
const mapSvg = $.parseHTML(html);
$("#tile-map").append(mapSvg);
Or simply copy HTML without jQ for example:
var mapSvg = document.getElementById("tile-map");
var arr = [
'<rect height="50" width="50" fill="blue"/>',
'<rect height="20" width="20" fill="green"/>'
]
var s = "<svg id='tile-map-svg' width=100 height=100>"+
arr.join('\n')+
"</svg>";
mapSvg.innerHTML = s;
mapSvg.innerHTML += s;
mapSvg.parentElement.innerHTML += mapSvg.outerHTML.replace(/</g,'<').replace(/>/g,'>');
<div style="background:lightblue; padding:10px;">
<div id="tile-map">
</div>
</div>
I'm trying to grab the first image in an html string like this one
<table border="0" cellpadding="2" cellspacing="7" style="vertical-align:top;"><tr><td width="80" align="center" valign="top"><font style="font-size:85%;font-family:arial,sans-serif"><img src="//t3.gstatic.com/images?q=tbn:ANd9GcQVyQsQJvKMgXHEX9riJuZKWav5U1nI-jdB-i1HwFYQ-7jGvGrbk9N_k0XEDMVH-HAbLxP1wrU" alt="" border="1" width="80" height="80" /><br /><font size="-2">Wall Street Journal</font></font></td><td valign="top" class="j"><font style="font-size:85%;font-family:arial,sans-serif"><br /><div style="padding-top:0.8em;"><img alt="" height="1" width="1" /></div><div class="lh"><b><b>Obama's</b> Letters to Corinthian</b><br /><font size="-1"><b><font color="#6f6f6f">Wall Street Journal</font></b></font><br /><font size="-1">The <b>Obama</b> Administration has targeted for-profit colleges as if they are enemy combatants. And now it has succeeded in putting out of business Santa Ana-based Corinthian Colleges for a dilatory response to document requests. Does the White House plan ...</font><br /><font size="-1" class="p"></font><br /><font class="p" size="-1"><a class="p" href="http://news.google.com/news/more?ncl=dPkBozywrsIXKoM&authuser=0&ned=us"><nobr><b>and more »</b></nobr></a></font></div></font></td></tr></table>
here is the tag of the image
<img src="//t3.gstatic.com/images?q=tbn:ANd9GcQVyQsQJvKMgXHEX9riJuZKWav5U1nI-jdB-i1HwFYQ-7jGvGrbk9N_k0XEDMVH-HAbLxP1wrU" alt="" border="1" width="80" height="80">
every images has got this kind of url
//tx.gstatic.com where x is a number i think between 0<x<3
That's what I do without success and I don't understand why this happen
var re = /<img[^>]+src="?([^"\s]+)"?\s*\/>/g;
var results = re.exec(HTMLSTRING);
var img="";
if(results!=null && results.length!=0) img = results[0];
The regular expression you provide indeed is not general enough to capture your <img> tag.
There are two options:
Make a better regular expression. This way lies madness. But in this case, it is sufficient to add the possibility of other attributes after src:
var re = /<img[^>]+src="?([^"\s]+)"?[^>]*\/>/g;
var results = re.exec(HTMLSTRING);
var img="";
if(results) img = results[1];
Note [^>]* replacing your \s*, and also note results[1] instead of results[0] if you want the source and not the tag itself.
Use a DOM parser to handle DOM. This is the easy path.
var jsdom = require("jsdom");
var img_sources = jsdom.env(
HTMLSTRING,
function (errors, window) {
var imgs = window.document.getElementsByTagName('img');
for (var i = 0; i < imgs.length; i++) {
var src = imgs[i].getAttribute('src');
if (src) console.log(src);
}
}
);
You could use the jQuery NPM module and do this:
var jQuery = require('jquery');
try {
var src = jQuery('YOUR_HTML_STRING').find('img')[0].src;
console.log('Output:\nSrc: ' + src + '\nNum: ' + (src.match(/\/\/t[0-3]/)[0])[3]);
} catch (e) {
console.log('Could not find <img>!');
}
How can I get the value of flashvars attribute?
<embed src="http://wl2static.lsl.com/common/flash/as3/MemberApplet026.swf"
id="opera_elb" width="100%"
height="100%"
allowscriptaccess="always"
allowfullscreen="true"
bgcolor="ffe8ef"
quality="high"
pluginspage="http://www.macromedia.com/go/getflashplayer"
type="application/x-shockwave-flash"
flashvars="muteaudio=0&ishd=1&ishq=0&twoway=0&proxyip=">
I am using getElementsByTagName to get the element.
var Em = content.document.getElementsByTagName('embed');
And replace values in flashvars
<script>
function myFunction()
{
var Em = content.document.getElementsByTagName('embed');
var str = Em[0].getAttribute('flashvars').innerHTML;
var res = str.replace("muteaudio=0","muteaudio=1");
document.getElementsByTagName("embed").innerHTML=res;
}
</script>
But when I try error: Uncaught ReferenceError: content is not defined
please help me.
Okay so here is a solution (strictly to change the attribute of flashvars!). First I think you have a few syntax errors within your JS. So I modified it and here is the JS:
function myFunction()
{
var Em = document.getElementById('vid');
var str = Em.getAttribute('flashvars');
var contentSpot = document.getElementById("he");
contentSpot.innerHTML = Em.getAttribute('flashvars');
Em.setAttribute('flashvars', 'muteaudio=1')
// contentSpot.innerHTML = Em.getAttribute('flashvars');/* I used this to see if the change occurred.*/
}
window.onload = myFunction();
So contentSpot is a div element I created to observe the change.
the html is here:
<embed id="vid" src="http://wl2static.lsl.com/common/flash/as3/MemberApplet026.swf"
id="opera_elb" width="100%"
height="100%"
allowscriptaccess="always"
allowfullscreen="true"
bgcolor="ffe8ef"
quality="high"
pluginspage="http://www.macromedia.com/go/getflashplayer"
type="application/x-shockwave-flash"
flashvars="muteaudio=0&ishd=1&ishq=0&twoway=0&proxyip=">
<div id="he"> Hello</div> <!-- The created div to observe -->
Okay so here is my suggestion:
1)pop in the cleaned up code into a jsfiddle, then observe the content.
2)Then remove the line: contentSpot.innerHTML = Em.getAttribute('flashvars'); above the code: Em.setAttribute('flashvars', 'muteaudio=1').
3) remove comments slashes and then hit ctrl + enter to observe the attribute change.
*really watch your "."/DOM syntax and case sensitivity.
Hope this helps you out!
I have a string
str = '<iframe width="100%" height="300" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="https://maps.google.com/maps?f=q&source=s_q&hl=vi&geocode=&q=Vimcom+91+b%C3%A0+tri%E1%BB%87u&aq=&sll=15.125395,108.795111&sspn=0.034096,0.038581&ie=UTF8&hq=Vimcom+91+b%C3%A0+tri%E1%BB%87u&hnear=&radius=15000&t=m&ll=21.011605,105.849323&spn=0.048074,0.051498&z=13&output=embed"></iframe><br /><small>Xem Bản đồ cỡ lớn hơn</small>'
How to get attr src using javascript (no-jquery) from str string?
Thank!
try this:
str.match(/.*src="([^"]+).*/)[1]
You can do this:
var str = '<iframe width="100%" height="300" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="https://maps.google.com/maps?f=q&source=s_q&hl=vi&geocode=&q=Vimcom+91+b%C3%A0+tri%E1%BB%87u&aq=&sll=15.125395,108.795111&sspn=0.034096,0.038581&ie=UTF8&hq=Vimcom+91+b%C3%A0+tri%E1%BB%87u&hnear=&radius=15000&t=m&ll=21.011605,105.849323&spn=0.048074,0.051498&z=13&output=embed"></iframe><br /><small>Xem Bản đồ cỡ lớn hơn</small>';
var div = document.createElement('div');
div.innerHTML = str;
alert(div.childNodes[0].getAttribute('src'));
http://jsfiddle.net/Dogbert/hxjpB/
Make sure the string starts with the <iframe> or the first childNode would be a textNode, and this wouldn't work. (There are more robust ways to do this which would work in those cases too, if you want.)
You may find interesting using regular expressions on your code: http://www.w3schools.com/jsref/jsref_obj_regexp.asp and http://www.w3schools.com/js/js_obj_regexp.asp
This regex should work:
/src="[^\ ]*"/i
I am having issues understanding why my jQuery index() function is not performing the way I expect it to. Perhaps I'm not understanding this. Let me show you.
I set up a new array. We'll use this later:
var mySources = new Array();
I have 5 images on my page:
<div id="homeSlides">
<img src="../images/homeImages/00.jpg" width="749" height="240" alt="myAltTag" />
<img src="../images/homeImages/01.jpg" width="749" height="240" alt="myAltTag" />
<img src="../images/homeImages/02.jpg" width="749" height="240" alt="myAltTag" />
<img src="../images/homeImages/03.jpg" width="749" height="240" alt="myAltTag" />
<img src="../images/homeImages/04.jpg" width="749" height="240" alt="myAltTag" />
I put them all in an jQuery object, like this:
var myImages = $("#homeSlides img");
Now, for each one, I extract the src attribute and push it into the mySources array like this:
$(myImages).each( function(index) {
mySources[index] = $(this).attr('src');
});
Now, I will run the array to the FireBug console to make sure it worked.
This...
console.log(mySources);
...returns this...
["../images/homeImages/00.jpg", "../images/homeImages/01.jpg", "../images/homeImages/02.jpg", "../images/homeImages/03.jpg", "../images/homeImages/04.jpg"]
...which is what I expect.
Now I do this:
var myVar = $(myImages).eq(2).attr('src');
Tracing that variable now...
console.log(myVar);
...returns this...
../images/homeImages/02.jpg
But then when I do this...
console.log('Index of ' + myVar + " is: " + ($(myVar).index( mySources )) );
...it returns this:
Index of ../images/homeImages/02.jpg is: -1
This is throwing me. Why would it return -1 for "not found" when it should be retunring 2. It does mat the second slot in the mySources array, no?
You are trying to use index() on an array. It is not intended to be used for anything other than jQuery element objects.
Using $.inArray() would be the better method
You may have the function backwards. Can you try:
$(mySources).index( myVar )