问题
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 bodyobject
. You needstring
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