I am working with a package that sends a string (html content) to my webhook that I need to replace with other text:
const x = `
<div dir="ltr">fifi<div><br></div>
<div><br></div>
<div><img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEcFPoHAAo1e7KR+MHvhg6PHwIjZvWTVNOvvH2+3kP1bO7mhPCuKXYKK5MAwrACJEACJOAeAhTeFN7umWlshQRIgARIgARIgARsToDCm8Lb5l8BDp8ESIAESIAESIAE3EOAwpvC2z0zja2QAAmQAAmQAAmQgM0JUHhTeNv8K8DhkwAJkAAJkAAJkIB7CFB4U3i7Z6axFRIgARIgARIgARKwOQEKbwpvm38FOHwSIAESIAESIAEScA8BCm8Kb/fMNLZCAiRAAiRAAiRAAjYnQOFN4W3zrwCHTwIkQAIkQAIkQALuIUDhTeHtnpnGVkiABEiABEiABEjA5gQovCm8bf4V4PBJgARIgARIgARIwD0EKLwpvN0z09gK9pWbcSvA01WdYa8nwCBAgQINCvBPpySO3L7603FKngLXj3hjr0GggQIECAwAot0J8Ca396r6WLUvAWvEvXlP4IECBAgACBjEBfCq196b1kPq7iDwvegnfxotIhAQIECBAgsHQCK2KYXRFf89J9Osv+rE4F7/8HxI8dO1ueh3UAAAAASUVORK5CYII=" alt="Screen Shot 2022-10-07 at 4.36.08 PM.png" width="335" height="483"><br></div>
</div>
`
The img is a blob file and is actually much longer, just shortened it for this. I figure the easiest way to find the part of the string is by the alt tag as I will have that string available to me. I am unsure how to proceed to have the entirety of <img .....> replaced with variable y. Any ideas?
You can try to replace <img ...> by regex
const x = `
<div dir="ltr">fifi<div><br></div>
<div><br></div>
<div><img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEcFPoHAAo1e7KR+MHvhg6PHwIjZvWTVNOvvH2+3kP1bO7mhPCuKXYKK5MAwrACJEACJOAeAhTeFN7umWlshQRIgARIgARIgARsToDCm8Lb5l8BDp8ESIAESIAESIAE3EOAwpvC2z0zja2QAAmQAAmQAAmQgM0JUHhTeNv8K8DhkwAJkAAJkAAJkIB7CFB4U3i7Z6axFRIgARIgARIgARKwOQEKbwpvm38FOHwSIAESIAESIAEScA8BCm8Kb/fMNLZCAiRAAiRAAiRAAjYnQOFN4W3zrwCHTwIkQAIkQAIkQALuIUDhTeHtnpnGVkiABEiABEiABEjA5gQovCm8bf4V4PBJgARIgARIgARIwD0EKLwpvN0z09gK9pWbcSvA01WdYa8nwCBAgQINCvBPpySO3L7603FKngLXj3hjr0GggQIECAwAot0J8Ca396r6WLUvAWvEvXlP4IECBAgACBjEBfCq196b1kPq7iDwvegnfxotIhAQIECBAgsHQCK2KYXRFf89J9Osv+rE4F7/8HxI8dO1ueh3UAAAAASUVORK5CYII=" alt="Screen Shot 2022-10-07 at 4.36.08 PM.png" width="335" height="483"><br></div>
</div>
`
const regex = /<img[^>]*>/g
const y = "Your variable"
const output = x.replaceAll(regex, y)
//if you want to replace for the first occurrence only
//you can use `replace` instead
//const output = x.replace(regex, y)
console.log(output)
Related
Is this possible using JavaScript or JQuery, or anything else?
Say I have an HTML file like this
<div>
<p>Hello World</p>
</div>
And I want to turn "World" into a span element itself, like so (so that I can style just "World")
<div>
<p>Hello <span>World</span></p>
</div>
Since there are a lot of unknowns in your question, so I am assuming that you already know the string/word around which you want to add the html tag.
So keeping that in mind, following solution should work:
HTML:
<div>
<p id="my-text">Hello World, Again!</p>
</div>
JavaScript:
const stringToBeReplaced = "World"; // what you want to replace
const innerText = document.getElementById("my-text").innerText; //grab the text
const beginIndex = innerText.indexOf(stringToBeReplaced); // get text where string begins
// if string exists
if (beginIndex >= 0) {
const textWithTag =
"<span style='color: red'>" + stringToBeReplaced + "</span>";
const newString = innerText.replace(stringToBeReplaced, textWithTag);
// replace the text with new string
document.getElementById("my-text").innerHTML = newString;
}
Hope this is what you were asking and looking for.
https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_replace3
str.replace solves the job. The comment of #Umer Hassan is correct.
I have api request which is string data type. It contains random plain text and img tag/ tags all combined all together. A string can have one or more img tags. I am looking the best way to slice those img tags from rest of the string and put it in an array.
"Random text <img src='img-one-src' alt='alt-one' /> some other random text <img src='img-two-src' src='alt-two' />"
The array can be:
var imgs = [{src: 'img-one-src', alt: 'alt-one'}, {src: 'img-two-src', alt: 'alt-two'}]
Create an element and make your string the innerHTML of that element. Then use querySelectorAll('img') on that element, and drag the result into an array using array spread [...res]. If instead of the elements you want the HTML strings in your array, simply use map():
const str ="Random text <img src='img-one-src' /> some other random text <img src='img-two-src' />";
const div = document.createElement('div');
div.innerHTML = str;
const images = [...div.querySelectorAll('img')];
const imageStrings = images.map(x=>x.outerHTML);
console.log(images, imageStrings);
You can use a regex for doing that.
let str = "Random text <img src='img-one-src' /> some other random text <img src='img-two-src' />";
console.log(str.match(/<img.+?\/>/g));
console.log(str.replace(/<img.+?\/>/g, ""));
I would like to convert a html code into text by using regexr.
I am a beginner and I don't really know how to do it with split() and replace()...
For example:
const = myArtcle {
article: <p class="some-style">Some text with 094blabla.</p>
<img src="#" /><p class="style"> etc...</p>.
}
I tried this:
const textArticle = myArticle.article;
const deleteHTML = new RegExp(/\<(.*?)\>/);
const parsingText = () => {
textArticle.split(deleteHTML, '');
return (textArticle);
}
And I would like to have a parahraph:
Some text with 094blabla. etc...
instead of the html tags with the paragraph (so I want to remove all the html tags and only get the paragraph)
I would like to do it with RegExr and function JavaScript only.
I have the following element stored as a String:
<div class="some-class" id="my-id" data-theme="black">
<strong data-animation="fade" disabled>Hello world!</strong>
</div>
I want to extract all the attributes names like this:
["class", "id", "data-theme", "data-animation", "disabled"]
This is what I tried to do, but I get also the values and dosent match the data-animation and disabled:
http://jsbin.com/hibebezibo/edit?js,console
EDIT:
Manged to get attributes using:
[\w-]+(?=\s*=\s*".*?")
But I still cant get the "disabled" prop.
Can someone explain me how to achieve this?
Thanks!
Using below regex which benefits from a positive lookahead you are able to match attributes' names:
[ ][\w-]+(?=[^<]*>)
Note: Adding - to character class is a must.
javascript code:
const HtmlElement = `<div class="some-class" id="my-id" data-theme="black">
<strong data-animation="fade" disabled>Hello world!</strong>
</div>`
console.log(HtmlElement.match(/ [\w-]+(?=[^<]*>)/g).map(function(element) {
return element.trimLeft();
}));
However it's not bulletproof as it can match words following a >. E.g:
<strong data-animation="fade" disabled>Hello world!></strong>
So it's recommended to accomplish such a task using DOM functionalities:
var html = document.createElement('div');
html.innerHTML = '<div class="some-class" id="my-id" xlink:href data-theme="black"><strong data-animation="fade" disabled>Hello world!</strong></div>';
var attrNodes = document.evaluate('//*/attribute::*', html, null, XPathResult.ANY_TYPE, null)
var nextAttrNode = attrNodes.iterateNext()
var arrAttrs = [];
while (nextAttrNode) {
arrAttrs.push(nextAttrNode.name)
nextAttrNode = attrNodes.iterateNext();
}
console.log(arrAttrs)
This works on even nested structure.
It returns element name and its attributes
\<([^\/\>"]+)\s{1,}([^"]+)=\"[^"]*\"
Test your own regex on https://regex101.com
Hello i made a code where i get the last part of the src data and replace _t for empty space like this.
// Get the current image number
var current = $(next.index("img"));
var nextUrl = next.attr("src").replace("_t", "");
This is the img example
<img src="http://farm1.static.flickr.com/28/66523124_b468cf4978_t.jpg" />
so in the example case i get this URL
http://farm1.static.flickr.com/28/66523124_b468cf4978
My question is ... I have to modify that code to actually change that at the beginin of the URL
in the Script im working now the thums are
<img id="extra_15" src="data/16/t_15_images.jpg" border="0" width="70px" class="">
And the big images are
<img id="extra_15" src="data/16/15_images.jpg" border="0" width="70px" class="">
how do i change that?
Switch around the pattern you are looking for. Instead of _t do t_.
var nextUrl = next.attr("src").replace("t_", "");