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>
CodePudding user response:
Append HTML to container element without innerHTML
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>