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)

2

1 Answer 1

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));

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.