0

I have dynamically generated HTML, for example:

const content = '<b>some <i>text</i><b>'

How can I get this content and remove last 2 letters, to get <b>some <i>te</i><b>? I'm getting this content via el.innerHTML. The main idea, I want to keep html how it is, and crop only text.

Volodymyr Humeniuk
  • 3,411
  • 9
  • 35
  • 70

1 Answers1

2

Using regex on HTML is... problematic.

An alternative method would be to create a new element, set its innerHTML to the string. Then update the text content of the i element.

const content = '<b>some <i>text</i><b>';
const span = document.createElement('span');
span.innerHTML = content;
const i = span.querySelector('i');
i.textContent = i.textContent.substring(0, i.textContent.length - 2);
console.log(span.innerHTML);
Andy
  • 61,948
  • 13
  • 68
  • 95
  • The only issue with this is you need to know the element that contains the text you want to manipulate. So in the OP's example, the text is in an ``. But since the OP said the HTML can be dynamic, I'm not sure that will always be the case. Still, this is a very good starting point. – JoshG Sep 12 '19 at 08:53