0

I'm using Quill Editor, which is basically a Box like in SO where you type in text and get HTML out. I store that HTML in a variable. Now my Website has a List of Tags (certain keywords) of brands and categories.

I would like a functionality to see if a Tag is inside that HTML. For example, my Author types The new Nike Store is open now I would need the Nike to be a Tag. It can be a span with a certain class.

What is the best way to accomplish this? I want to check before publishing as live detection is not needed.

My Solution for now:

I didn´t implement it yet, but I think I would try to check every word inside my tag list before going to the next and wrapping it in the needed HTML Tags if the word is a Tag. But this could get messy to code because of all the other stuff like the other HTML Tags that get generated through the editor.

tomerpacific
  • 3,092
  • 8
  • 22
  • 41
Badgy
  • 2,852
  • 11
  • 35

1 Answers1

1

Assuming that the author types just plain text, you can use a regular expression to search for tag words (or phrases) and replace the phrase in the HTML with that phrase, surrounded in a span with your new class:

const input = 'The new Nike Store is open now';
const htmlStr = input.replace(/\bnike\b/gi, `<span class="tag">$&</span>`);
document.body.appendChild(document.createElement('div')).innerHTML = htmlStr;
.tag {
  background-color: yellow;
}

Or, for dynamic tags, create the pattern dynamically:

const input = 'The new Nike Store is open now';
const tags = ['nike', 'open'];
const pattern = new RegExp(tags.join('|'), 'gi');
const htmlStr = input.replace(pattern, `<span class="tag">$&</span>`);
document.body.appendChild(document.createElement('div')).innerHTML = htmlStr;
.tag {
  background-color: yellow;
}

(if the tags can contain characters with a special meaning in a regular expression, escape them first before passing to new RegExp)

CertainPerformance
  • 260,466
  • 31
  • 181
  • 209
  • Thanks for the answer so far this is defenetly helpful, one thing I need to modify is probably the Quill API to get the Index Location of the Text im replacing with the Tag, an im 99% sure that there is no way for me to get the non html String Version of the content – Badgy Nov 29 '18 at 06:40