0

I am trying to parse through strings to find emoji identified with shortcodes :thing: and then replace them with an image <img src="thing.png" />.

I thought I was all set using a function as the replacement method but I can not figure how to do this returning the HTML rather than this string. I tried to build the image using createElement too but that just returned [object Object]

const container = document.getElementById('result');

const testArray = [
    ':cat: fixed something',
    ':godmode: cool new feature',
    ':feelsgood: :godmode: Much emoji',
  ];
  
  const imgObj = {
    "cat": "https://github.githubassets.com/images/icons/emoji/unicode/1f431.png?v8",
      "godmode": "https://github.githubassets.com/images/icons/emoji/godmode.png?v8",
      "feelsgood" :  "https://github.githubassets.com/images/icons/emoji/feelsgood.png?v8"

}

const reg = /:([a-zA-Z]+):/g;

//  search for :colon: shortcodes and remove colons, use as key for object

function replacer(match) {
    // remove the colons
    let emo = match.split(':').join('');
// THIS IS BROKEN - returns string instead of HTML element I want
    let imgSrc = imgObj[emo];
    return '<img src="' + imgSrc + '" /> ';
  }
  
  testArray.forEach((commit) => {
   let formatted =   commit.replace(reg, replacer);
   container.append(formatted);
    container.appendChild(document.createElement('br'));

  });
<div id="result">
</div>
Zac
  • 12,637
  • 21
  • 74
  • 122

1 Answers1

2

Append HTML to container element without innerHTML

insertAdjacentHTML

const container = document.getElementById('result');

const testArray = [
    ':cat: fixed something',
    ':godmode: cool new feature',
    ':feelsgood: :godmode: Much emoji',
  ];
  
  const imgObj = {
    "cat": "https://github.githubassets.com/images/icons/emoji/unicode/1f431.png?v8",
      "godmode": "https://github.githubassets.com/images/icons/emoji/godmode.png?v8",
      "feelsgood" :  "https://github.githubassets.com/images/icons/emoji/feelsgood.png?v8"

}

const reg = /:([a-zA-Z]+):/g;

//  search for :colon: shortcodes and remove colons, use as key for object

function replacer(match) {
    // remove the colons
    let emo = match.split(':').join('');
// THIS IS BROKEN - returns string instead of HTML element I want
    let imgSrc = imgObj[emo];
    return '<img src="' + imgSrc + '" /> ';
  }
  
  testArray.forEach((commit) => {
   let formatted =   commit.replace(reg, replacer);
   container.insertAdjacentHTML('beforeend', formatted);
    container.appendChild(document.createElement('br'));

  });
<div id="result">
</div>
Konrad
  • 21,590
  • 4
  • 28
  • 64
  • Be aware this will of course render any HTML tags that are in the testArray,. If this is not what the OP wants, an easy fix is to escape the Input, then do the replace.. – Keith Nov 07 '22 at 20:15