Oleg
Oleg

Reputation: 3014

Need to find occurrence of string and replace with another one

I need to parse html string and replace sources of images with it's base64 data.

for example:

input html:

<p>This is some text</p>
<p><img src="sys_attachment.do?sys_id=e57ff4badb984300e330b04ffe9619ce" alt="" width="auto" height="auto" /> &nbsp;</p>

I need to extract sys_id value from src="sys_attachment.do?sys_id=e57ff4badb984300e330b04ffe9619ce" and replace the entire src with it's base64 alternative, to get something like this:

<p>This is some text</p>
<p><img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAkEAAAIKCAY....." alt="" width="auto" height="auto" /> &nbsp;</p>

I tried this, but it's not working as expected

var htmlString = '<img src="sys_attachment.do?sys_id=e57ff4badb984300e330b04ffe9619ce"/>';

var res = htmlString.match(/^<img src="sys_attachment.do?sys_id=.*"$/g);

Any ideas how this can be solved?

Upvotes: 0

Views: 75

Answers (1)

Sagar V
Sagar V

Reputation: 12478

Get src using htmlString.match(/=.*/)[0].replace("=",'');.

Change it to Base64 using btoa.

var htmlString = '<img src="sys_attachment.do?sys_id=e57ff4badb984300e330b04ffe9619ce"/>';
var sys_id = htmlString.match(/=.*/)[0].replace("=",'');
sys_id = btoa(sys_id);
htmlString = htmlString.replace(/src=\"[^"]*"/,'src="data:image/png;base64,'+sys_id+'"');
console.log(htmlString);

Upvotes: 1

Related Questions