How can I get the next or previous character of findText()

独自空忆成欢 提交于 2019-12-20 07:39:41

问题


How can I get the next or previous character of findText().

function myFunction() {
var doc = DocumentApp.getActiveDocument();
var str = doc.getbody();
var i = "f";
var x = str.findText(i);
var y = str[str.index(x)-1];
Logger.log(y);
}

It is not working. and get some error.

Example: string = "Abcdefgh" , var x=string.findText("f"); after found "f"; want to get previous char of "f". which is "e" in this case. I want to know special function in google script to get


回答1:


Flow:

  • getBody() returns a body object. You need string type. getText() returns string.
  • Use regexp#exec to get previous and next character of the search string

Snippet:

function myFunction() {
  var doc = DocumentApp.getActiveDocument();
  var str = doc.getBody().getText();//modified
  var search = "f";
  var regx = new RegExp("(.)"+search+"(.)")
  var y = regx.exec(str);
  Logger.log(y);
  if (y !== null){ Logger.log("Previous character" + y[1]).log("Next character:" + y[2])}
}

To practice:

  • Regexp#exec
  • Doc#body


来源:https://stackoverflow.com/questions/57742521/how-can-i-get-the-next-or-previous-character-of-findtext

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!