简体   繁体   中英

Get current word in google-apps-script

Just started working with Google-apps-script and for the most part it is pretty straight forward. I am having trouble though being able to get the current word the user is typing / where the cursor is.

ie, if | represents my cursor and I was typing the word "hello" and was in this state hello| I want to return hello as a string.

I've tried many variations to get this, but can't seem to find how in the api.

var doc = DocumentApp.getActiveDocument();
var word = doc.getCursor().getElement().asText().getText();

If I had hello all| (cursor at the end of all) I'd get the entire string 'hello all' back. I am hoping there is a way to just pick off the last element (after the last space).

Thanks in advance!

This gives you the last complete word:

function myFunction() {
  var doc = DocumentApp.getActiveDocument();
  var words = doc.getCursor().getElement().asText().getText().split(' ');
  Logger.log(words[parseInt(words.length)-2]);
}

This gives you the last word you where typing on:

function myFunction() {
  var doc = DocumentApp.getActiveDocument();
  var words = doc.getCursor().getElement().asText().getText().split(' ');
  Logger.log(words[parseInt(words.length)-1]);
}

You should change the split method with the correct regex to enable puntuation and enters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM