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
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
Related
I am having the following code for appending table in Google Docs.
var sss = SpreadsheetApp.openById('id of spreadsheet');
var rawData = sss.getDataRange().getValues()
var data = []
for (var i = 0; i< rawData.length; i++){
tempData=[]
tempData=[rawData[i][1],rawData[i][2],rawData[i][3]]
data.push(tempData)
}
var someDoc = DocumentApp.openById(someId);
var body = someDoc.getBody();
body.appendTable(data).editAsText().setBold(false);
This code works fine. The problem is that there is url in rawdata[i][3]. It gets displayed in Google doc as plain text. How can I convert it into hyperlink? It would be even better if it is possible to write it as body.appendParagraph("my link").setLinkUrl("http://www.google.com"). The problem is that it is in an array, not in paragraph.
I believe your goal is as follows.
You want to put a table to Google Document by retrieving the values from Google Spreadsheet.
In your Spreadsheet, the column "D" has the hyperlinks. And, you want to set the value as the hyperlink.
In this case, how about the following modification?
Modified script:
var sss = SpreadsheetApp.openById('id of spreadsheet');
var rawData = sss.getDataRange().getValues();
var data = []
for (var i = 0; i < rawData.length; i++) {
tempData = []
tempData = [rawData[i][1], rawData[i][2], rawData[i][3]]
data.push(tempData)
}
var someDoc = DocumentApp.openById(someId);
var body = someDoc.getBody();
// I modified below script.
var table = body.appendTable(data);
for (var r = 0; r < table.getNumRows(); r++) {
var obj = table.getCell(r, 2).editAsText();
var text = obj.getText();
if (/^https?:\/\//.test(text)) obj.setLinkUrl(text);
}
table.editAsText().setBold(false);
When this script is run, a table is put using the values retrieved from Spreadsheet. And, about the column "C" of the table, the text is changed to the hyperlink.
Note:
This modified script supposes that your values of column "D" are like https://### and http://###. Please be careful about this.
If you want to give the specific text (for example, click here) with the hyperlink, please modify as follows.
From
if (/^https?:\/\//.test(text)) obj.setLinkUrl(text);
To
if (/^https?:\/\//.test(text)) obj.setText("click here").setLinkUrl(text);
References:
getCell(rowIndex, cellIndex) of Class Table
setLinkUrl(url)
You can try the following to make all URLs in a Google Doc clickable:
function urlClickable() {
var urlRegex = 'http[s]?:\/\/[^ ]+';
var doc = DocumentApp.openById('yourDocId');
var body = doc.getBody();
var urlElement = body.findText(urlRegex);
while (urlElement != null) {
var text = urlElement.getElement().asText();
var startOffset = urlElement.getStartOffset();
var endOffset = urlElement.getEndOffsetInclusive();
text.setLinkUrl(startOffset, endOffset, getUrl(text.getText()));
urlElement = body.findText(urlRegex, urlElement);
}
}
function getUrl(text) {
var startOffset = text.indexOf('http');
var endOffset = text.indexOf(' ', startOffset);
if (endOffset === -1) {
endOffset = text.length;
}
return text.substring(startOffset, endOffset);
}
I want to make bold a string stored in a variable called boldtext. I want a simple one line code for this. I am not from coding background. Please help
Edit 1:
I made mistake in my original question. So, I am putting the question again.
My need = I want variable boldtext to be bold.
function calendar() {
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Course');
var user = Session.getActiveUser().getUsername(); //gives user name
var firstpart = user.split('.')[0]; //gives first part of user name
var uppercase = firstpart.charAt(0).toUpperCase() + firstpart.substring(1);//makes first letter upper case
var boldtext = 'Nice work, ' + uppercase //This has to be made bold
var bold = SpreadsheetApp.newTextStyle().setBold(true).build();
var boldname = SpreadsheetApp.newRichTextValue().setText(boldtext).setTextStyle(boldtext.indexOf(uppercase), boldtext.length, bold).build(); //mistake is here by me.
spreadsheet.getRange('X53').setValue(boldname + 'Reminder is added to your calendar');
function myFunction() {
var user = Session.getActiveUser().getUsername();
var first = user.split('.')[0];
var name = first[0].toUpperCase() + first.substring(1);
var text = 'Nice work, ' + name;
var bold = SpreadsheetApp.newTextStyle().setBold(true).build();
var value = SpreadsheetApp.newRichTextValue().setText(text).setTextStyle(text.indexOf(name), text.length, bold).build();
SpreadsheetApp.getActiveSheet().getRange('A1').setRichTextValue(value);
}
Reference
Class RichTextValueBuilder
Updated variant
function calendar() {
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Course');
var user = Session.getActiveUser().getUsername();
var firstpart = user.split('.')[0];
var name = firstpart[0].toUpperCase() + firstpart.substring(1);
var boldtext = 'Nice work, ' + name;
var bold = SpreadsheetApp.newTextStyle().setBold(true).build();
var text = ' Reminder is added to your calendar';
var value = SpreadsheetApp.newRichTextValue().setText(boldtext + text).setTextStyle(0, boldtext.length, bold).build();
spreadsheet.getRange('X53').setRichTextValue(value);
}
I hope everyone is in good health.
My main goal
So main goal was to get the hyperlink and the text linked with it. I initially used code as below :
var ekArr = [];
function myFunction() {
var doc= DocumentApp.getActiveDocument();
var isCell4Blank1 = doc.getBlob().getDataAsString();
var data = Utilities.parseCsv(isCell4Blank1);
var linku = doc.getBody().getTables()[0].getCell(2,1);
var t = doc.getBody().getTables()[0].getCell(2,1).getText();
Logger.log("link is. " + linku);
// Logger.log(doc.getBody().getText());
for(var find in data){
var fi = data[find].toString().includes("http");
if(fi===true){
var newArr = data[find].toString().split(" ");
var output = newArr[1].replace("(","").replace(")","").replace(">>>>","")
ekArr.push(output);
}
}
var tex = doc.getBody().getText();
var fo = tex.split(ekArr[0]);
Logger.log(tex);
doc.getBody().getTables()[0].getCell(2,2).setText(ekArr);
doc.getBody().getTables()[0].getCell(2,3).setText(t);
Logger.log(ekArr);
return ekArr;
}
I need to extract the links and content from the cells of a table.
From above code I am able to extract the links however I am not able to extract the text linked with it.
Also I have another code which helped me to extract the links and text but from googlesheets. As I am new to google docs I want to modify the below code according to google docs.
function sheetFunction() {
var sheet= SpreadsheetApp.getActiveSheet();
var isCell4Blank1 = sheet.getRange("A1").isBlank();
if (!isCell4Blank1) {
var linkData =
sheet.getRange("A1").getRichTextValue().getRuns().reduce((ar, e) => {
var url = e.getLinkUrl();
Logger.log(url);
if (url) {
var color = e.getTextStyle().getForegroundColor();
var startIndex = e.getStartIndex();
var endIndex = e.getEndIndex();
var text = e.getText()
ar.push(color);
ar.push(text);
ar.push(startIndex);
ar.push(endIndex);
ar.push(url);
}
return ar;
}, [])
}
Use the methods getText() and getLinkUrl()
Sample based on your first code snippet:
function myFunction() {
var doc = DocumentApp.getActiveDocument();
var linku = doc.getBody().getTables()[0].getCell(2,1);
Logger.log("link text is: " + linku.getText());
Logger.log("link is: " + linku.getLinkUrl());
}
i'm trying to do a match and return function: search barcode and a size value in a sheet, and add it to a textbox in a sidebar
something went wrong - script do not return any values
var barcodeBox = document.getElementById("bcdn");
var typeBox = document.getElementById("stype");
var sizeBox = document.getElementById("size");
document.getElementById("butn").addEventListener("click",addRecord);
document.getElementById("bcdn").addEventListener("input",getStype);
function getStype(){
var bCode = document.getElementById("bcdn").value;
if(bCode.length === 10){
google.script.run.withSuccessHandler(updateSize).getSize(bCode);
}else{
document.getElementById("size").value = "-";
M.updateTextFields();
} // end Else
} // end getStype
function updateSize(size){
document.getElementById("size").value = size;
M.updateTextFields();
}
this is gs code
function getSize(bCode){
var ws = SpreadsheetApp.getSheetByName("Barcode List");
var data = ws.getRange(1,1,ws.getLastRow(),2).getValues();
var bCodeList = data.map(function(r){return[0];});
var sizeList = data.map(function(r){return[1];});
var position = bCodeList.indexOf(bCode);
if(position > -1){
return sizeList[position].toFixed(2);
}else{
return "";
}
bCode seems to be just a value but bCodeList is an array of arrays so bCodeList.indexOf(bCode) is probably always going to be -1
Maybe change this var bCodeList = data.map(function(r){return[0];});
to this var bCodeList = data.map(r => 0);
Of course sizeList has the same problem
Missing get spreadsheet
Wrong return of map
Not converting [][] into [] for indexOf
var ws = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Barcode List");
var data = ws.getRange(1,1,ws.getLastRow(),2).getValues();
var bCodeList = data.map(function(r){return r[0];}).flat();
var sizeList = data.map(function(r){return r[1];}).flat();
I have a Google Spreadsheet with different columns and I've put as variable in my code var COLUMN_URL = 10 ;so now I would like to change in order to search the column URL which is in the first row of the sheet so I wrote this code :
var COLUMN_URL = function find_COLUMN_URL(){
var tss = SpreadsheetApp.openById(SPREADSHEET_ID);
var sheet = tss.getSheets()[0];
var data = sheet.getRange(1,1,1,1).getValues();
for(n=0;n<data.length;++n){
if(data[0][n].toString().match('URL')=='URL')
return n;
}
}
and I deleted the var COLUMN_URL = 10 but when I execute the code as I did with the previous declaration in the main fonction I doesn't work .Do you have an idea why is not working?Thank you.
Edit: I've changed in a different version like this :
function find_column_projet(){
var tss = SpreadsheetApp.openById(SPREADSHEET_ID);
var sheet = tss.getSheets()[0];
var lastColumn = sheet.getLastColumn() + 1;
var data = sheet.getRange(1,1,1,lastColumn).getValues();
for(n=0;n<data.length;n++){
if(data[0][n].toString().match('URL')=='URL')
COLUMN_URL = n + 1 ;
}
function show_URL(){
find_column_projet();
Logger.log('The URL ' + COLUMN_URL);
}
and in the log I have URL undefined and I don't get it where is the problem.I want to recuperate the first row and search for the URL and then return the number of the column.
I think you have forgotten to store the value returned by the find_column_projet() function, in the second version of your code:
function show_URL(){
var COLUMN_URL = find_column_projet();
Logger.log('The URL ' + COLUMN_URL);
}
The first iteration of your code is assigning COLUMN_URL to the function itself:
var COLUMN_URL = function find_COLUMN_URL(){
//...
}
when these operations should be separate:
function find_COLUMN_URL(){
}
var COLUMN_URL = find_COLUMN_URL();