I want to extract html codes from a textarea value but failed.
I want to detect and replace images with textarea value.
Below is an example of what I want to do.
TEXTAREA
<textarea ><img src="x1"><img src="x2"></textarea>
The code below is an example of what I want to do, I know it's wrong.
var editor_images = $('.editor').val().find('img');
editor_images.each(function(key, value) {
$(this).attr('src','example');
});
CodePudding user response:
If you want to replace multiple attributes or tags, then your question may be too broad. However, the example below gives you an idea of how to replace an image attribute within the textarea:
function replaceValueOfTextArea(searchAttr, replaceAttr, value) {
const editor = document.querySelector('.editor');
const imgs = editor.value.match(/<img[a-zA-Z0-9="' ] >/g);
let textAreaNewValue = '';
for (let img of imgs) {
const regMatch = new RegExp(`(?<!img)${searchAttr}`, "gi");
const match = img.match(regMatch);
if (match) {
const regAttr = new RegExp(`${searchAttr}=["|'][^"|'] ["|']`, "gi");
textAreaNewValue = img.replace(regAttr, `${replaceAttr}="${value}"`);
} else {
textAreaNewValue = img;
}
}
editor.value = String(textAreaNewValue);
}
replaceValueOfTextArea('src', 'src', 'https://example.com');
<textarea ><img src="x1"><img alt="x2"></textarea>
CodePudding user response:
You can use jQuery's $.parseHTML()
to parse an HTML string into DOM nodes. Then you can use this method to turn them back into HTML before reinserting them in your <textarea>
:
// Get contents of editor as HTML and parse into individual <img> nodes:
let nodes = $.parseHTML( $('.editor').val() )
// Map through <img> nodes and change src attribute, and return as HTML text:
let html = nodes.map(function(node){
$(node).attr('src', 'example')
return $('<div>').append($(node).clone()).html();
})
// Insert HTML text back into editor:
$('.editor').html( html.join('') )
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea ><img src="x1"><img src="x2"></textarea>