I have a string contaning some html markup, like this:
var html = "<div>
<img src="http://test.com/image1.png" />
<h1>SOME TEXT</h1>
<img src="http://text.com/image2.jpg" />
</div>";
i want to replace all urls inside src="..."
It is ok if i do html = html.replace(/[^-]src\=["|'](.*?)['|"]/g, "SOME_URL");
then all src="..." become src="SOME_URL"
But now i want to replace each match with a different string, taken from an array, but i'm having trouble with this.
I think i have to use a function for the replacement, but not sure how to implement it.
Something like:
html = html.replace(/[^-]src\=["|'](.*?)['|"]/g, function ($0, $1){ //what do i do here??? });
So, if i have:
var arr = [];
arr['http://test.com/image1.jpg']='file1';
arr['http://test.com/test.jpg']='file3';
the html string from above will become:
"<div>
<img src="file1" />
<h1>SOME TEXT</h1>
<img src="http://text.com/image2.jpg" />
</div>"
Note that 'http://text.com/image2.jpg' is not a key of the array, so it does not gets replaced.
Any help appreciated, thank you in advance.
var html = '<div><img src="http://test.com/image1.jpg" />...</div>';
var arr = {
'http://test.com/image1.jpg' : 'file1',
'http://test.com/test.jpg' : 'file3'
}
html = html.replace(/[^-]src\=["|'](.*?)['|"]/g, function ($0, $1){
return ' src="' + (arr[$1] || $1) + '"';
});
console.log(html) returns
"<div><img src="file1" /><h1>SOME TEXT</h1><img src="http://text.com/image2.jpg" /></div>"
I'd forget about regex in this case, if you have an array containing all urls and their individual replacements in an object, why not do something like:
for (i in replaceObj)
{
html = html.split(i).join(replaceObj[i]);
}
tried it in console:
html = '<div><img src="imgs/img.jpg"/></div>';
replaceObj = {};
replaceObj['imgs/img.jpg'] = 'file';
for(i in test){html = html.split(i).join(replaceObj[i])};
output: <div><img src="file"/></div>. You could split on src="'+i'"' and concat. the same when joining to be on the safe side... but bottom line: keep it simple, whenever you can
Related
I use ajax get a json like this:
{"dataStore":"[{\"delete_flag\":\"false\",\"id\":\"74\",\"icon_img\":\"img/a5.jpeg\"}]"}
How to append "delete_flag" , "id" , "icon_img" to 3 different places on html ?
You can use this pure javascript method like below.
The code basically uses document.getElementById() to get the element, and .innerHTML to set the inside of the element to the value of the object.
This code (and the code using jQuery) both use JSON.parse() to parse the data into the correct object that our code can read. The [0] at the end is to select the object we wanted since it would give us an array (and we want an object).
const result = {"dataStore":"[{\"delete_flag\":\"false\",\"id\":\"74\",\"icon_img\":\"img/a5.jpeg\"}]"};
const parsedData = JSON.parse(result.dataStore)[0];
document.getElementById("delete_flag").innerHTML = parsedData.delete_flag;
document.getElementById("id").innerHTML = parsedData.id;
document.getElementById("icon_img").src = parsedData.icon_img;
<div id="delete_flag"></div>
<div id="id"></div>
<img id="icon_img">
Or you can use jQuery (which in my opinion, is much simpler). The code below uses .html() to change the inside of the divs to the item from the object, and .attr() to set the attribute src to the image source you wanted.
const result = {"dataStore":"[{\"delete_flag\":\"false\",\"id\":\"74\",\"icon_img\":\"img/a5.jpeg\"}]"};
const parsedData = JSON.parse(result.dataStore)[0];
$("#delete_flag").html(parsedData.delete_flag);
$("#id").html(parsedData.id);
$("#icon_img").attr("src", parsedData.icon_img);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="delete_flag"></div>
<div id="id"></div>
<img id="icon_img">
you can use jQuery .html() or .text()
For example:
var json = {"id" : "74"};
$( "#content" )
.html( "<span>This is the ID: " + json.id + "</span>" );
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div id="content"></div>
</body>
</html>
Just use some simple JavaScript parsing:
const jsonData = {"dataStore":"[{\"delete_flag\":\"false\",\"id\":\"74\",\"icon_img\":\"img/a5.jpeg\"}]"};
const parsedData = JSON.parse(jsonData.dataStore)[0];
document.getElementById("delFlag").textContent = "Delete Flag: " + parsedData["delete_flag"];
document.getElementById("id").textContent = "ID: " + parsedData["id"];
document.getElementById("img").textContent = "Image: " + parsedData["icon_img"];
<p id="delFlag"></p>
<p id="id"></p>
<p id="img"></p>
Note that you can't parse the full object jsonData because it's not JSON - only the data inside it is JSON.
I've upvoted the other answers, but maybe this will help someone else. On your ajax success function, do something like this:
success: function(data){
// console.log('succes: '+data);
var delete_flag = data['delete_flag'];
$('#results').html(delete_flag); // update the DIV or whatever element
}
if you got real fancy, you could create a for loop and put all the json variable you need into an array and create a function to parse them all into their proper elements; you could learn this on your own fairly easily.
var data = {
"dataStore": {
"delete_flag": "false",
id: "74"
}
}
$('.flag').html(data.dataStore.delete_flag);
$('.id').html(data.dataStore.id);
span {
color: red
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Flag: <span class="flag"></span>
<hr />
ID: <span class="id"></span>
I have a string like this.
x = '<div class="sample">
<img src="http://www.example.com/i/java.png">
</div>
<div class="sample_another">
<img src="/i/somedir/python.png">
</div>'
I want to convert to this
x = '<div class="sample">
<img src="http://www.example.com/i/java.png" height="200px" width="100px">
</div>
<div class="sample_another">
<img src="/i/somedir/python.png" width="150px" height="150px">
</div>'
input string will be a html doc. for all the images in the doc, i want to add the height and width property. and to get the height and width property i have to use something like this
var img = new Image();
img.onload = function() {
alert(this.width + 'x' + this.height);
}
img.src = 'http://www.example.com/intl/logo.gif';
p.s. i tried using this solution but the problem i face is that the string might have the script tag and DOM parses it as a closing script tag. I cant find much for regex either. So is there any other way to obtain this result ?
Thanks.
If you can remove scripts than go with this code:
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
var string ="<script type"text/javascript"></script><img alt=''
src='http://api.com/images/UID' /><br/>Some plain text<br/><a
href='http://www.google.com'>http://www.google.com</a>";
var elem= document.createElement("div");
$(string).find('script').remove();
elem.innerHTML = string;
var images = elem.getElementsByTagName("img");
for(i=0; i<images.length; i++){
images[i].width = "150";
images[i].height = "250";
}
string = elem.innerHTML;
Problem you are facing with is that it turns out that HTML5 does not allow script tags to be dynamically added using the innerHTML property. So you will need to add them dynamically on some other way.
This is some code that might help you:
var my_awesome_script = document.createElement('script');
my_awesome_script.setAttribute('src','http://example.com/site.js');
document.head.appendChild(my_awesome_script);
I have this strange issue where URL parameter divider & of an IMG SRC gets replaced with the HTML entity.
I need to replace those so this string:
<img src="https://example.com/imagehandler?$PNG%20with%20alpha$&scl=1" alt="">
Returns:
<img src="https://example.com/imagehandler?$PNG%20with%20alpha$&scl=1" alt="">
It should only replace within double quotes — not if in other places like regular HTML entities.
A regex workaround:
var text = `<img src="https://example.com/imagehandler?$PNG%20with%20alpha$&scl=1" alt="">`;
console.log(text.replace(/src="[^"]+/g, function(match) {
return match.replace('&', '&');
}));
A DOM solution:
According to your statement, It's a string, not in the dom..., you should use DOMParser to convert a HTML string into valid DOM. Modifying #prasad's answer it would be something like this:
var HTMLmarkup = `
<img src="https://example.com/imagehandler?$PNG%20with%20alpha$&scl=1" alt="">
<img src="https://example.com/imagehandler?$PNG%20with%20alpha$&scl=1" alt="">
`
var parser = new DOMParser()
var dom = parser.parseFromString(HTMLmarkup, "text/html");
dom.querySelectorAll('img').forEach(function(a){
console.log(a.src)
})
Try with simple regex pattern /&/g .And querySelectorAll used for select the img element
Demo regex
document.querySelectorAll('img').forEach(function(a){
a.src = a.src.replace(/&/g,"")
console.log(a.src)
})
<img src="https://example.com/imagehandler?$PNG%20with%20alpha$&scl=1" alt="">
For completeness, here's a solution that uses regular DOM functions. It diverges from the original requirement in that it extracts the URL because (IMHO) it's a reasonable ultimate goal:
var html = '<img src="https://example.com/imagehandler?$PNG%20with%20alpha$&scl=1" alt=""> <img src="/some/other/location/?one=1&two=2&three=3">';
var aux = document.createElement("div");
aux.innerHTML = html;
var urls = [];
aux.querySelectorAll("img[src]").forEach(function(image){
urls.push(image.getAttribute("src"));
});
console.log(urls);
I currently have:
//javascript
function morshots()
{
var mordor = document.getElementById("ss1");
var shots= (
mordor.innerHTML = <img src="http://i.imgur.com/83HCt.png" alt="scrns1"><img src="http://i.imgur.com/5mWIy.png" alt="scrns2"><img src="http://i.imgur.com/pPafl.png" alt="scrns3">;
}
and
<!--html-->
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="screenshots.js"></script>
</head>
<body>
<div id="ss1">
<button onClick="morshots();">View Screenshots</button>
</div>
</body>
</html>
Currently the button does nothing on click. What I want is for the images to replace the button on the page. This is not my entire code, however I omitted the non-pertinent piece of code for readability.
--EDIT--
I have added escapes for the inner quotes and non-escaped quotes around the image tags. I am still getting the same result with the page (button click does nothing)
function morshots()
{
var mordor = document.getElementById("ss1");
mordor.innerHTML = '<img src=\"http://i.imgur.com/83HCt.png\" alt=\"scrns1\"><img src=\"http://i.imgur.com/5mWIy.png\" alt=\"scrns2\"><img src=\"http://i.imgur.com/pPafl.png\" alt=\"scrns3\">';
}'
---EDIT2:----
Fixed it, the working code reads:
function morshots()
{var mordor = document.getElementById("ss1");
mordor.innerHTML = '<img src=\"http://i.imgur.com/83HCt.png\" alt=\"scrns1\"><img src=\"http://i.imgur.com/5mWIy.png\" alt=\"scrns2\"><img src=\"http://i.imgur.com/pPafl.png\" alt=\"scrns3\">';
}
Add the <img>s within quotes:
function morshots()
{
var mordor = document.getElementById("ss1");
mordor.innerHTML = '<img src="http://i.imgur.com/83HCt.png" alt="scrns1"><img src="http://i.imgur.com/5mWIy.png" alt="scrns2"><img src="http://i.imgur.com/pPafl.png" alt="scrns3">';
}
Did you check your JavaScript console for errors?
// syntax error:
var shots= (
// syntax error:
mordor.innerHTML = <img src="http://i.imgur.com/83HCt.png" alt="scrns1"><img src="http://i.imgur.com/5mWIy.png" alt="scrns2"><img src="http://i.imgur.com/pPafl.png" alt="scrns3">;
You need to pass a string to mordor.innerHTML - wrap your html in quotes. I'm not sure what you're trying to do with shots.
Add quotes and escape them withing html adding backslash \ before them:
var mordor = document.getElementById("ss1");
mordor.onclick = function () {
var shots= "<img src=\"http://i.imgur.com/83HCt.png\" alt=\"scrns1\"><img src=\"http://i.imgur.com/5mWIy.png\" alt=\"scrns2\"><img src=\"http://i.imgur.com/pPafl.png\" alt=\"scrns3\">";
mordor.innerHTML = shots;
};
I have a javascript variable I need to create like this:
var HTMLContent = '<div class="className">HTML Content</div>';
How can I format it in an easier to read format because I'm going to want to create multiple lines of HTML.
e.g.
var HTMLContent = '
<div class="className">
HTML Content
</div>
';
Is something like that possible?
It would also be good if I could import via URL e.g. var HTMLContent = 'http://domain.com/page.html';
var longStr = "You can split\
the string onto multiple lines\
like so";
An example using your HTML would be:
var longStr =
'<div class="className">\
HTML Content\
</div>';
To load external HTML, check out jQuery's load method:
$('#result').load('ajax/test.html');
In your page markup, add a hidden template div, like:
<div id="contentTemplate" style="display: none;">
<div class="className">
HTML_CONTENT
</div>
</div>
...then in your JavaScript, you can do something like:
var newContent = 'The content for the new element';
var templateContent = document.getElementById("contentTemplate").innerHTML;
var htmlContent = templateContent.replace("HTML_CONTENT", newContent);
You could also use an AJAX request to pull the value of newContent from a URL to get your dynamic content loading working. If you plan on doing this, however, then I suggest you investigate using a framework like jQuery, which can greatly simplify this process.
You can also use backticks
function myFunc() {
var HTMLContent =`
<div class="className">
<div>HTML Content</div>
</div>
`;
document.getElementById('demo').innerHTML = (HTMLContent);
}
myFunc()
<div id="demo"></div>
var HTMLContent =
'<div class="className">' +
'HTML Content' +
'</div>';
You can do something like:
var HTMLContent = '<div class="ClassName">' +
'HTML Content' +
'</div>';
You can use escape characters:
var HTMLContent = '<div class="className">\n\tHTML Content\n</div>';
I may have misinterpretted the question, you want the javascript to be more readable, not the html stored in the variable?
var HTMLContent = "" +
"<div class=\"className\">\n" +
" HTML Content\n" +
"</div>\n" +
"";
This way, the script that writes it it pretty and the code it writes will be pretty too if someone were to view-source.