Ali
Ali

Reputation: 51

jquery find and replace a word in string to make it bold between estaric and

Is there any library or custom function which can find the text and make it bold i.e wiki text to html works. Actually I want to process a text which should work the way whatsapp and skype works.

var textString = "A text which should be *bold*  _Italic_  and ~Strike~ ";

I want it to bold the word bold and italic to word italic with jquery on the basis of *,_ and ~ sign

Upvotes: 2

Views: 344

Answers (1)

solanki...
solanki...

Reputation: 5098

let textString = "A text which should be *bold*  _Italic_  and ~Strike~ ";

const check = [{
  reg: /\*(.*)\*/gm,
  class: 'bold'
}, {
  reg: /_(.*)_/gm,
  class: 'italic'
}, {
  reg: /~(.*)~/gm,
  class: 'strike'
}];
let newStr = '';
check.map(x => {
  const regx = x.reg.exec(textString);
  const replace = "<span class='" + x.class + "'>" + regx[1] + "</span>";
  const spl = textString.split(regx[0]);
  newStr = spl[0] + replace + spl[1];
  textString = newStr;
});
document.getElementById('foo').innerHTML = newStr;
.italic{
  font-style: italic;
}

.strike {
  text-decoration: line-through;
}

.bold {
  font-weight: bold;
}
<div id="foo"><div>

Upvotes: 2

Related Questions