Reputation: 65
Firstly, I'm using google apps script I get an text body and I want to replace placeholder with variables in a sheet, I get a variable in my sheet and i want to replace it with regex but it's not working
it's working with a variable that i just set but not with an value that i get in a sheet... I don't know why...
function replaceInBody() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
var lastLigne = sheet.getLastRow()
var lastColumn = sheet.getLastColumn()
var firstLigne = sheet.getRange(1,1,1,lastColumn).getValues();
var newBody
Logger.log('firstLigne: %s', firstLigne)
var data
var bodyTest = 'blablabla {name} blablabla {var1} blabla'
Logger.log('bodyTest: %s', bodyTest)
var notwork = firstLigne[0][2]
var work = 'name'
Logger.log('notwork: %s', notwork) // finally it's work by rewriter the code
Logger.log('work: %s', work)
Logger.log('**')
Logger.log(new RegExp("{"+ work +"}", 'g'))
newBody = bodyTest.replace(new RegExp("{"+ notwork +"}", 'g'), 'changed')
Logger.log('newBody: %s', newBody)
newBody = bodyTest.replace(new RegExp("{"+ work +"}", 'g'), 'changed')
Logger.log('newBody: %s', newBody)
}
```
just my text is not change with notwork variable but it's the same variable... // finally it's work by rewriter the code but I don't know my first mistake thanks to all of you :p
Upvotes: 0
Views: 925
Reputation: 1379
You need to change your replace()
method to:
var regex1 = 'blablabla {name} blablabla {name} blabla';
console.log(regex1.replace(/name/g, 'Changed'));
This will find every appearance of "name" and change it. You can take a look at the method's documentation to see how to work with these more simply.
Upvotes: 1