Need to capture beginning of word

In this plunk I have a CodeMirror editor with a function that on F5 it needs to capture from the first letter of the word until the letter where the cursor is located. For example, if the cursor is located on the word ‘white’, right after the letter ‘h’, then the function needs to return ‘wh’. If the cursor is located right after the last letter of the word, then the entire word needs to be returned.

The plunk works sometimes, so obviously there’s something wrong, when it doesn’t work the ‘From’ and ‘To’ characters are at the same position even when the cursor is at the end of the word. Any help will be greatly appreciated.

This is the attempt:

	editor.setOption("extraKeys", {
	  "F5": function(cm) {
		  var cursor = editor.getCursor();
		  var word = cm.findWordAt(cursor);
		  console.log("From character: " +
		  console.log("To character: " +
		  console.log(cm.getRange(word.anchor, cursor));

findWordAt will return a range around a piece of whitespace if the cursor is in front of whitespace, so it’s probably not doing what you expect it to do here.

Any hints as to what function should I use instead? I can’t find it in the API documentation. Thanks.

There is no built-in function that does this for you, you’ll have to scan through the text yourself.