How to replace a string with another string in JS? - javascript

I am fetching data (html content) from an API and setting it as an dangerioslyinnerhtml in ReactJS. I want to make an image popup using fancyapps/UI and in order to do that, I have to replace this,
<div className="img-parent">
<img className='fancybox' src="" alt="" />
</div>
with this
<Fancybox options={{ infinite: false }}>
<button
data-fancybox="gallery"
data-src={require("source-of-image")}
className="button button--secondary">
<img className='fancybox' src={require("source-of-image")} alt="" />
</button>
</Fancybox>
Any ideas with .replaceAll function in JS?
I tried to explain my problem in details and I want some experienced people to help.

An approach would be to parse the response you are getting as html as explained here:
const parser = new DOMParser();
const htmlDoc = parser.parseFromString(txt, 'text/html');
and then you get the data you need to display your FancyBox components like this:
const images = [];
htmlDoc.querySelectorAll(".img-parent img").forEach(img=>{
images.push({src:img.src, alt:img.alt})
});

Related

Why is my QR code cropped when extracting with base64?

im trying to copy the qr code from another windows but the left first line of the qr is missing
Script (renderer.js):
const loadQr = async () => {
const response = await window.loader.loadQr()
// console.log(response)
document.getElementById('qr').src = 'data:image/png;base64,' +
response
}
console.log('Index Loaded')
loadQr()
And my HTML is:
<div class="btns">
<button onclick="loadQr()">Load QR</button>
</div>
<br>
<img id ="qr" width="264" height="264" src="" alt="qr">
<script src='../renderer.js'></script>
And Im also adding a sc so you understand what im dealing with:
https://imgur.com/a/8y5izKx
Thanks in advance :)

Unable to get image src url with Cheerio

At the moment I am trying to get value in src= of
<div class="page-break no-gaps">
<img id="image-0" src="https://foo.bar/image.jpg" class="wp-image" alt="Title">
</div>
with the following code:
getImageSrc(imageObj: Cheerio | undefined): string {
let image
image = imageObj?.attr('src')
console.log(image)
}
selector code:
chapterDetailsSelector = 'div.page-break > img'
However all I am getting is undefined
EDITED - add more context
View source html != what is fetched by cheerio
Seems like the image url is in attr('data-cfsrc') rather than attr('data') when fetched with cheerio

How to display HTML received in JSON using React

JSON
var obj = {
content: "<p class="p1">Sample p tag one.</p> <p class="p1">Also
another paragraph sample.</p> <p><b>sample text</b></p> <p>More info <a
title="" href="https://www.google.com/"
target="_blank" rel="noopener"><em>THE WORK AHEAD: MACHINES, SKILLS AND
U.S. LEADERSHIP</em></a></p>"
};
How would I render this code in react? It shows all of the html tags.
Through dangerouslySetInnetHTML.
const htmlString = '<p>My html</p>';
const innerHtmlObject = {
__html: htmlString,
};
<div dangerouslySetInnerHTML={innerHtmlObject} />
Note: This is a bad practice that can lead to security vulnerability!
You can try this
<div
dangerouslySetInnerHTML={{
__html: this.state.obj.content
}}
/>
You need to parse the HTML.
You can do this through dangerouslySetInnerHTML but it's safer to sanitize it first using something like html-react-parser.
import Parser from 'html-react-parser';
Inside you render function:
<div>{Parser(obj.content)}</div>

retrieving gifs from tenor API json

i'm implementing this tenor API into my Site....the thing is that with this function I retrieve a single value single gif...How do I foreach() all of them?
How would need to be the html structure and the javascript loop
JAVASCRIPT/ JSON
function grab_data(anon_id)
{
// set the apikey and limit
var apikey = "*************";
var lmt = 8;
.....
// callback for trending top 10 GIFs
function tenorCallback_trending(responsetext)
{
// parse the json response
var response_objects = JSON.parse(responsetext);
top_10_gifs = response_objects["results"];
// load the GIFs -- for our example we will load the first GIFs preview size (nanogif) and share size (tinygif)
document.getElementById("preview_gif").src = top_10_gifs[1]["media"][0]["nanogif"]["url"];
document.getElementById("share_gif").src = top_10_gifs[6]["media"][0]["tinygif"]["url"];
return;
}
I would have this top_10_gifs variable loaded of content...how do I foreach it?
HTML
<h2 class="title">GIF loaded - preview image</h2>
<div class="container">
<img id="preview_gif" src="" alt="" style="">
</div>
<h2 class="title">GIF loaded - share image</h2>
<div class="container">
<img id="share_gif" src="" alt="" style="">
</div>
Depends on what exactly you're trying to do (which you haven't explained), but something like
response_objects.results.forEach((gifObj, i) => {
if (i >= 8) return;
// do something with each gifObj
document.querySelector('.container')
.appendChild(document.createElement('img'))
.src = gifObj.media[0].tinygif.url;
});
to iterate over all of them.

Get Image Url From RSS MEDIUM FEED

I am trying to display each image from each post from medium's rss feed, without using JQuery, but only javascript or angular, in HTML.
Is it possible to get the image from the RSS feed? I am receiving the title, the date it was created at and the link.
I am working with Ionic2.
entries: any = null;
image: any = null;
In my constructor:
Feed.load('https://medium.com/feed/#jaymelone', (err, rss) => {
if (err) {
console.log(err);
}
else {
this.entries = rss.items;
this.image = this.entries.find('img').eq(0).attr('src');
}
console.log("RSS function - entries:", this.entries);
console.log("RSS function - image: ", this.image);
});
In my HTML
<div class="post" *ngFor="let entry of entries">
<div class="inner">
<img class="img" [src]="entry.image">
<p class="title">{{entry.title}}</p>
</div>
</div>
But I receive:
<img class="img" src="undefined">
And:
TypeError: Array.prototype.find callback must be a function
Assuming that your console.log call is outputting the image name correctly, everything looks in order except you need to use ng-src instead of src, like this:
<img class="img" ng-src="{{entry.image}}">
Try entry.image.url.
Example:
<img class="img" [src]="entry.image.url">

Categories

Resources