0

I want to be able to split strings while preserving HTML tags inside of them.

I am working on making a small typewriter effect for my website, but I want to be able to preserve HTML formatting while doing the effect.

e.g. Getting the first 10 characters of Hello, <strong>World</strong>! would result in Hello, <strong>Wor</strong>

Is there an easy way to do this in JS? If not, what would be the best way that I do this (i.e. should I use regex or just vanilla JS)

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • You have to parse the text and preserve tags. It might help to read [*RegEx match open tags except XHTML self-contained tags*](https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags). – RobG Aug 16 '21 at 20:25
  • Thanks for your help! Will look into it :D – Impossible Reality Aug 16 '21 at 20:26

1 Answers1

1

function innerSubstring(s, indexStart, indexEnd) {
  let result = [];
  let insideTag = false;
  let index = 0;
  for (let i = 0; i < s.length; ++i) {
    if (insideTag) {
      if (s[i] === ">") {
        insideTag = false;
      }
    } else {
      if (s[i] === "<") {
        insideTag = true;
      } else {
        if (index < indexStart || indexEnd <= index) {
          ++index;
          continue;
        }
        ++index;
      }
    }
    result.push(s[i]);
  }
  return result.join("");
}

const s = "Hello, <strong>World!</strong>";
console.log(s);
console.log(innerSubstring(s, 0, 10));
console.log(innerSubstring(s, 2, 4));
console.log(innerSubstring(s, 8, 10));
console.log(innerSubstring(s, 2, 8));
console.log(innerSubstring(s, 2, 1000));
kol
  • 27,881
  • 12
  • 83
  • 120