Simple search and replace in userscript?

I’m wondering what would be the most straightforward way to do a global search and replace operation on all the text in the current file, from within userscript code. I realize I could do ko/editor getValue() into a variable, do the replacement operation on the contents of that variable, and then do ko/editor setValue(). But to see if there is something more straightforward using a single statement, I recorded a macro, and ended up with something that very much looks like legacy code (which I know I’m not supposed to be using):
ko.find.replaceAllInMacro(window, 0, 'x', 'x', true, 0, 0, false, false);

Any suggestions?

Hi, I don’t think there is a “simple” function (that is not legacy) that does this. If you want to stick to the SDK editor API, getValue() and setValue() will work, but the current scroll position and any bookmarks, etc. will be lost during the operation. It may be advantageous to just use the legacy API for the time being.

You could also mix the following methods in the ko/editor SDK to achieve the result you want:

  • findString
  • setSelection
  • replaceSelection

Covered here:

Thank you, @mitchell and @nathanr. Since I’m not concerned about the scroll position and any bookmarks in this scenario, getValue() and setValue() can be Plan B. In the meantime, I can look into using findString, setSelection, and replaceSelection.