[英]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
bla bla bla 橙色 bla bla
After:后:
bla bla (orange image) in 56px x 56px for exemple.
例如,bla bla(橙色图像)为 56px x 56px。
Replace() use string to string i don't think you can use it for image. Replace() 使用字符串到字符串,我认为您不能将它用于图像。
Thank you very much for your time and i hope it was not a duplicate (i searched for 2hours before writing this)非常感谢您的时间,我希望它不是重复的(我在写这篇文章之前搜索了 2 小时)
This could be used as ref: https://github.com/mdn/webextensions-examples/tree/master/emoji-substitution这可以用作参考: 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.但是,如果您想使用实际图像,您仍然可以使用
String.replace()
。 You would just replace with HTML and pass the overall string to something like Element.innerHTML
.您只需替换为 HTML 并将整个字符串传递给类似
Element.innerHTML
。 In other words, "orange" would get replaced with <img class="icon" src="https://..." alt="Orange" />
.换句话说,“orange” 将被替换为
<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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.