Replace double space but cursor goes back to the beginning

Hello !

In a Prosemirror editor (latest version), I’m trying to replace 2 consecutive spaces with 1 space && 1 non breaking space. I’m using this code:

    string
      .replace(/( {2,})/g, function (_, __, p2) {
        return [...Array(p2.length).keys()].reduce((a) => `${a}\xa0`, ' ')
      })

Replace works like a charm but it has a curious side effect. At the end of each line, if I add a regular space, the cursor goes back to the beginning of the editor and space is erased.

But, if I add this line to my function:

    string
      // eslint-disable-next-line @typescript-eslint/typedef
      .replace(/( {2,})/g, function (_, __, p2) {
        return [...Array(p2.length).keys()].reduce((a) => `${a}\xa0`, ' ')
      })
      .replace(/ $/g, '\xa0') // add this

the replace works and cursor stays where it is when I add a space.

Could someone explain this behaviour to me ?

1 Like

Where are you performing these replaces?

I’m using it in a new Schema called text:

text: {
        group: 'inline',
        toDOM(node: PMNode) {
          return replaceWhitespace(node.text)
        }
      }

with replaceWhitespace being an helper function I described above.

I play around a lot to understand what’s happening and I’m confused. I removed everything related to “replace white space” and the cursor still goes back to the beginning of the editor after I hit the space bar. And this small line replace(/ $/g, '\xa0') in the replace function fixing this.

You really don’t want to be changing the text in your toDOM function. That text will be read from the DOM again when it changes, so your modified text will end up in the document.

I’ve deleted every thing linked to space replacement and the cursor is still jumping. So issue is somewhere else, I “just” have to find where :thinking:

This line replace(/ $/g, '\xa0') was added years ago along with htmlClean so maybe it’s a clue