2

So on my node.js backend I have an object with a content property which contains an HTML string. Now in there there is an img element where I would like to replace the attribute src, which is now a base64 string, to a path to my uploads folder. How can I change this src attribute?

this is req.body.content. I would like to replace the base64 src of the img element to something I choose

{ content: '<p><br></p><p><img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAOEAAADhCAMAAAAJbSJIAAAAmVBMV.. }

2 Answers 2

3

If you know for sure that there is just one image in your string, you can use a regular expression to replace:

let new_content = content.replace(/src="[^"]+"/, 'src="new contents of the attribute"');

This will replace every src attribute in your html, so make sure you don't have multiple.
If you have a more specific need, I normally use cheerio (https://www.npmjs.com/package/cheerio) to load in html and edit it like I would in jquery(-ish).

(The [^"]+ in the regular expression stand for "Match multiple characters that are not "", which is normally how I select something inside a known boundary)

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, I'll have a look at both options :)
2

you can replace that string with a regular expression

let newPath = "some/where/local/img.png";
let replaced = req.body.content.replace(/src="(.+?)"/igm, "src='"+newPath+'")

if you don't know the html structure and e.g need to find all images, you should use something like cheerio or jsdom to parse the html string, make changes in the virtual dom.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.