Collapse whitespace before tr.replace()

I have the start and end position of a decoration. I want to remove that word/annotation on button click, so I call, This works but I have whitespace remaining that I want to clean up.

e.g. "the club always." [ --> tr.replace(10, 16) --> ] "the club .", I want to collapse the whitespace to reflect "the club."

Any pointers gratefully received

I seem to have a solution but feel like there’s something in PM I’m missing that would do this better?

  const selection = state.doc.resolve(deco.from);

  if (selection) {
    const { nodeBefore } = selection;

    if (nodeBefore.isText && nodeBefore.nodeSize) {
      const { textContent } = nodeBefore;
      const textContentReversed = textContent.split("").reverse().join("");
      const trimLen =\S/);

      if (trimLen) {
        // expand range to include preceeding whitespace
        deco.from = deco.from - trimLen;

:man_facepalming: That regex should be this…

      const trimLen =\S|$/);