Skip to content

Replace a specific character from a string with HTML tags

Having a text input, if there is a specific character it must convert it to a tag. For example, the special character is *, the text between 2 special characters must appear in italic.

For example:

This is *my* wonderful *text*

must be converted to:

This is <i>my</i> wonderful <i>text</i>

So I’ve tried like:

const arr = "This is *my* wonderful *text*";
 if (arr.includes('*')) {
      arr[index] = arr.replace('*', '<i>');

it is replacing the star character with <i> but doesn’t work if there are more special characters.

Any ideas?


You can simply create wrapper and thereafter use regular expression to detect if there is any word that is surrounded by * and simply replace it with any tag, in your example is <i> tag so just see the following


let str = "This is *my* wonderful *text*";
let regex = /(?<=*)(.*?)(?=*)/;
while (str.includes('*')) {
  let matched = regex.exec(str);
  let wrap = "<i>" + matched[1] + "</i>";
  str = str.replace(`*${matched[1]}*`, wrap);