I don't know shite about:

Replace string by position

Use substring to replace a string at a start end end point

While building a cross-posting script on idkshite.com I needed to replace jsx components in my .mdx files with Liquid tags that can be understood by dev.to’s editor. The parser that i’m using to find all incompatible jsx components provides the start and end position of the component inside of the markdown string. So I couldn’t directly use String.replace(stringToFind, replaceWithThis). To solve this problem, I came across this useful method to replace a string by a given position.

Replace by position

The basic idea is creating 2 substrings before and after the content to be replaced. Then you construct a new string from the first substring + the new content + second substring. Inside the result your text has been successfully replaced.

function replaceByPosition({
}: {
  text: string;
  position: {start: number, end: number};
  replaceWith: string
}) {
  return (
    text.substring(0, position.start) +
    replaceWith +
    text.substring(position.end + 1)