Move Cursor to End of Line, before Any Carriage Return/Line Feed

Greetings, folks!

I have an action Javascript (appended below) that moves the cursor to the end of the current line, but if there is a carriage return or line feed at the end of the line, it will move the cursor to the start of the next line. Not what I want.

Simply subtracting one character from the line length is a shoddy workaround, but only fails if the line is the last line in the text file.

Thoughts or suggestions?

(Please forgive me for being so rusty in JS!)

Blessings, and thank you!


// Move cursor to end of line

let [loc, len] = editor.getSelectedLineRange(),
str = editor.getTextInRange(loc, len);
editor.setTextInRange(loc, len, str);

// editor.setSelectedRange(loc + str.length, 0); // this includes the carriage return/line feed at the end of lines, and thus going to the start of the next line instead

editor.setSelectedRange(loc + str.length - 1, 0); // the shoddy workaround



It’s not a shoddy workaroundβ€”you have to deal with the fact that there’s a linefeed at the end of all but (possibly) the last line. But it is worth the effort to deal with that special case. Here’s a solution I believe works no matter where you are in the file:

let [loc, len] = editor.getSelectedLineRange();
let str = editor.getTextInRange(loc, len);
str = str.replace(/\n$/, "");
editor.setSelectedRange(loc + str.length, 0);

The replace strips the trailing newline from str if there is one. Now the length of str is just what you want.

(I’m assuming, by the way, that the usual keyboard shortcuts of βŒ˜β†’ and βŒƒE aren’t available to you, either because this is part of a longer script or you’re working without a physical keyboard.)


God Bless You!

(and thank you for being so gracious! :wink: )