简体   繁体   中英

replace all occurrences of a string in JavaScript to image for a firefox extension

I would like to change every occurrences of certains strings to the image it correspond to.

Exemple:

Before:

bla bla bla orange bla bla

After:

bla bla (orange image) in 56px x 56px for exemple.

Replace() use string to string i don't think you can use it for image.

Thank you very much for your time and i hope it was not a duplicate (i searched for 2hours before writing this)

This could be used as ref: https://github.com/mdn/webextensions-examples/tree/master/emoji-substitution

(I am not looking to do emoji but images)

If you're looking to replace with emoji (like 🍊), you don't need to do anything special - that's still just text. But, you can still use String.replace() if you want to use actual images. You would just replace with HTML and pass the overall string to something like Element.innerHTML . In other words, "orange" would get replaced with <img class="icon" src="https://..." alt="Orange" /> . For example:

 const replaceImages = str => Object.entries({ orange: { src: 'https://www.flaticon.com/svg/static/icons/svg/167/167265.svg', alt: 'Orange', }, // ...add more replacements here... }).reduce( (result, [key, {src, alt}]) => result.replace(key, `<img src="${src}" alt="${alt}" class="icon" />`), str ) document.querySelector('.js-container').innerHTML = replaceImages('bla bla bla orange bla bla')
 .icon { height: 1em; }
 <div class="js-container"></div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM