Google Script, how can use variables with regex search? - regex

Very inexperienced coder here, I have recently gotten a script working that uses regex to search for two different words occurring within a certain word limit. So I can search for "the" and "account" occurring within 10 words of each other, then my script prints the sentence it occurs in. However, my work requires me to search for lots of different work combinations and it has become a pain having to enter each word manually into the string /\W*(the)\W*\s+(\w+\s+){0,10}(account)|(account)\s+(\w+\s+){0,10}(the)/i; for example.
I would like to have something in the script where I can enter the words I want to search for just once, and they will be used in the string above. I have tried, what I think is, declaring variables like this:
var word1 = the
var word2 = account
/\W*(word1)\W*\s+(\w+\s+){0,10}(word2)|(word2)\s+(\w+\s+){0,10}(word1)/i;
But, again, very experienced coder so I'm a little out of my depth. Would really like something like the script snippet above to work in my full script listed below.
Here is my full working script without my attempt at declaring variables mentioned above:
var ss = SpreadsheetApp.getActiveSpreadsheet();
var historySheet = ss.getSheetByName('master');
var resultsSheet = ss.getSheetByName('results');
var totalRowsWithData = historySheet.getDataRange().getNumRows();
var data = historySheet.getRange(1, 1, totalRowsWithData, 3).getValues();
var regexp = /\W*(the)\W*\s+(\w+\s+){0,10}(account)|(account)\s+(\w+\s+){0,10}(the)/i;
var result = [];
for (var i = 0; i < data.length; i += 1) {
var row = data[i];
var column = row[0];
if (regexp.exec(column) !== null) {
result.push(row); }}
if (result.length > 0) {
var resultsSheetDataRows = resultsSheet.getDataRange().getNumRows();
resultsSheetDataRows = resultsSheetDataRows === 1 ? resultsSheetDataRows : resultsSheetDataRows + 1;
var resultsSheetRange = resultsSheet.getRange(resultsSheetDataRows, 1, result.length, 3);
resultsSheetRange.setValues(result);}}
I tried this solution but not sure I have done it correctly as it only enters results in logs and not printing in the "results" sheet:
var ss = SpreadsheetApp.getActiveSpreadsheet();
var historySheet = ss.getSheetByName('Sheet1');
var resultsSheet = ss.getSheetByName('Results1');
var totalRowsWithData = historySheet.getDataRange().getNumRows();
var data = historySheet.getRange(1, 1, totalRowsWithData, 3).getValues();
const regexpTemplate = '\W*(word1)\W*\s+(\w+\s+){0,10}(word2)|(word2)\s+(\w+\s+){0,10}(word1)';
var word1 = 'test1';
var word2 = 'test2';
var regexpString = regexpTemplate.replace(/word1/g, word1).replace(/word2/g, word2);
var regexp = new RegExp(regexpString, 'i');
Logger.log(regexp); // /W*(the)W*s+(w+s+){0,10}(account)|(account)s+(w+s+){0,10}(the)/i
var result = [];
for (var i = 0; i < data.length; i += 1) {
var row = data[i];
var column = row[0];
if (regexp.exec(column) !== null) {
result.push(row); }}
if (result.length > 0) {
var resultsSheetDataRows = resultsSheet.getDataRange().getNumRows();
resultsSheetDataRows = resultsSheetDataRows === 1 ? resultsSheetDataRows : resultsSheetDataRows + 1;
var resultsSheetRange = resultsSheet.getRange(resultsSheetDataRows, 1, result.length, 3);
resultsSheetRange.setValues(result);}}

Use the RegExp contructor.
const regexpTemplate = '\\W*(word1)\\W*\\s+(\\w+\\s+){0,10}(word2)|(word2)\\s+(\\w+\\s+){0,10}(word1)';
var word1 = 'the';
var word2 = 'account';
var regexpString = regexpTemplate.replace(/word1/g, word1).replace(/word2/g, word2);
var regexp = new RegExp(regexpString, 'i');
Logger.log(regexp); // /\W*(the)\W*\s+(\w+\s+){0,10}(account)|(account)\s+(\w+\s+){0,10}(the)/i
You can put this into a function to easily generate your new regular expression whenever you want to update the words.
/**
* Generate the regular expression with the provided words.
* #param {String} word1
* #param {String} word2
* #returns {RegExp}
*/
function generateRegExp(word1, word2) {
const regexpTemplate = '\\W*(word1)\\W*\\s+(\\w+\\s+){0,10}(word2)|(word2)\\s+(\\w+\\s+){0,10}(word1)';
var regexpString = regexpTemplate.replace(/word1/g, word1).replace(/word2/g, word2);
return new RegExp(regexpString, 'i');
}
/**
* Test the generateRegExp() function.
*/
function test_generateRegExp() {
var word1 = 'the';
var word2 = 'account';
var regexp = generateRegExp(word1, word2); // /\W*(the)\W*\s+(\w+\s+){0,10}(account)|(account)\s+(\w+\s+){0,10}(the)/i
// Use regexp just as you do in your script
// i.e. if (regexp.exec(column) !== null) { result.push(row); }
}
Your final script could look something like this.
function printSentences() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var historySheet = ss.getSheetByName('Sheet1');
var resultsSheet = ss.getSheetByName('Results1');
var totalRowsWithData = historySheet.getDataRange().getNumRows();
var data = historySheet.getRange(1, 1, totalRowsWithData, 3).getValues();
var result = [];
var regexp = generateRegExp("the", "account");
for (var i = 0; i < data.length; i += 1) {
var row = data[i];
var column = row[0];
if (regexp.exec(column) !== null) {
result.push(row);
}
}
if (result.length > 0) {
var resultsSheetDataRows = resultsSheet.getDataRange().getNumRows();
resultsSheetDataRows = resultsSheetDataRows === 1 ? resultsSheetDataRows : resultsSheetDataRows + 1;
var resultsSheetRange = resultsSheet.getRange(resultsSheetDataRows, 1, result.length, 3);
resultsSheetRange.setValues(result);
}
}
/**
* Generate the regular expression with the provided words.
* #param {String} word1
* #param {String} word2
* #returns {RegExp}
*/
function generateRegExp(word1, word2) {
const regexpTemplate = '\\W*(word1)\\W*\\s+(\\w+\\s+){0,10}(word2)|(word2)\\s+(\\w+\\s+){0,10}(word1)';
var regexpString = regexpTemplate.replace(/word1/g, word1).replace(/word2/g, word2);
return new RegExp(regexpString, 'i');
}

Related

Google Sheet Script - if else, checking if cells match

looking for some help with the function below. I'm trying to have it check if a file has been updated in Google Drive before running a import script. I have it down to checking if two dates/times match in a sheet, but I can't seem to get it to correctly register whether they match. It should either be when S3 <> T3 or when U3 = FALSE. Any help would be greatly appreciated!!
function syncCSVtransactions() {
var ss = SpreadsheetApp.getActiveSpreadsheet()
var sh = ss.getSheetByName("LOOKUP")
var cell_trnsnew = sh.getRange("S3");
var cell_trnsold = sh.getRange("T3");
var cell_trnscheck = sh.getRange("U3");
if( cell_trnsnew != cell_trnsold ){ //this is the line giving trouble
var source_file = DriveApp.getFilesByName("data_export.csv").next();
var csvData = Utilities.parseCsv(source_file.getBlob().getDataAsString());
var sheet2 = ss.getSheetByName('trs');
sheet2.getRange(1, 1, csvData.length, csvData[0].length).setValues(csvData);
cell_trnsnew.copyTo(cell_trnsold, {contentsOnly:true});
chartupdate();
} else {
}
}
I think that in your script, var cell_trnsnew = sh.getRange("S3");, var cell_trnsold = sh.getRange("T3"); and var cell_trnscheck = sh.getRange("U3"); can be written by one call. And, although I'm not sure about the values of your "LOOKUP" sheet, how about the following 2 patterns?
Pattern 1:
In this pattern, it supposes that the values of "S3", "T3" and "U3" are the date object, the date object and boolean, respectively.
From:
var cell_trnsnew = sh.getRange("S3");
var cell_trnsold = sh.getRange("T3");
var cell_trnscheck = sh.getRange("U3");
if( cell_trnsnew != cell_trnsold ){
To:
var [cell_trnsnew, cell_trnsold, cell_trnscheck] = sh.getRange("S3:U3").getValues()[0];
if (cell_trnsnew.getTime() != cell_trnsold.getTime() || cell_trnscheck === false) {
Pattern 2:
In this pattern, the values of "S3", "T3" and "U3" are used as the string values.
From:
var cell_trnsnew = sh.getRange("S3");
var cell_trnsold = sh.getRange("T3");
var cell_trnscheck = sh.getRange("U3");
if( cell_trnsnew != cell_trnsold ){
To:
var [cell_trnsnew, cell_trnsold, cell_trnscheck] = sh.getRange("S3:U3").getDisplayValues()[0];
if (cell_trnsnew != cell_trnsold || cell_trnscheck == "FALSE") {
References:
getValues()
getDisplayValues()

Regex in Google App Script to enclose each word inside an Array inside quotes

For example I want to enclose each word in the following array inside quotes.
{seguridad=0, funcionalidad=1, instalaciones=si, observaciones=si,
areas=Pasillos, limpieza=no, pintura=tal vez}
Into:
{"seguridad"="0", "funcionalidad"="1", "instalaciones"="si",
"observaciones"="si", "areas"="Pasillos", "limpieza"="no",
"pintura"="tal vez"}
This is my unsuccesful script so far.
function Enclose() {
var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty("1iXQxyL3URe1X1FgbZ76mEFAxLnxegyDzXOMF6WQ5Yqs"));
var sheet = doc.getSheetByName("json");
var sheet2 = doc.getSheetByName("tabla de frecuencias");
var rows = sheet.getDataRange();
var numRows = rows.getNumRows();
var values = rows.getValues();
var prelast = sheet.getRange("A1:A").getValues();
var last = prelast.filter(String).length;
var json = sheet2.getRange("B11").getValues();
var regExp = new RegExp("/[\w]+", "g");
/* var match = json.replace(regExp,""); */
var match = regExp.exec(match);
sheet2.getRange("C11").setValue("\"" + match + "\"");
}
You may try the following approach :
First you wrap all , and = by quotes "" by using the following regex:
/(\s*[,=]\s*)/
Then you replace the opening brackets separately using the following two regex:
/(\s*{)/gm
/(\s*})/gm
const str = `{seguridad=0, funcionalidad=1, instalaciones=si, observaciones=si, areas=Pasillos, limpieza=no, pintura=tal vez}`;
var result = str.replace(/(\s*[,=]\s*)/gm,`"$1"`);
result=result.replace(/(\s*{)/gm,`$1"`);
result=result.replace(/(\s*})/gm,`"$1`);
console.log(result);
How about this sample?
Sample script :
var json = "{seguridad=0, funcionalidad=1, instalaciones=si, observaciones=si, areas=Pasillos, limpieza=no, pintura=tal vez}";
var res = json.replace(/(\d+|[a-zA-Z]+)=(\d+|[a-zA-Z\s]+)/g, "\"$1\"=\"$2\"");
Logger.log(res)
Result :
var json = "{seguridad=0, funcionalidad=1, instalaciones=si, observaciones=si, areas=Pasillos, limpieza=no, pintura=tal vez}";
var res = json.replace(/(\d+|[a-zA-Z]+)=(\d+|[a-zA-Z\s]+)/g, "\"$1\"=\"$2\"");
console.log(res)
When this is reflected to your script, the modified script is as follows.
Modified script :
function Enclose() {
var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty("1iXQxyL3URe1X1FgbZ76mEFAxLnxegyDzXOMF6WQ5Yqs"));
var sheet = doc.getSheetByName("json");
var sheet2 = doc.getSheetByName("tabla de frecuencias");
var rows = sheet.getDataRange();
var numRows = rows.getNumRows();
var values = rows.getValues();
var prelast = sheet.getRange("A1:A").getValues();
var last = prelast.filter(String).length;
var json = sheet2.getRange("B11").getValue();
// var regExp = new RegExp("/[\w]+", "g");
// /* var match = json.replace(regExp,""); */
// var match = regExp.exec(match);
match = json.replace(/(\d+|[a-zA-Z]+)=(\d+|[a-zA-Z\s]+)/g, "\"$1\"=\"$2\"");
sheet2.getRange("C11").setValue("\"" + match + "\"");
}

Replacing Google Doc text with Spreadsheet Data using RegEx

I am making a merge code to take data from my spreadsheet and populate merge tags in a Google Doc. The part of the code I am unable to write correctly is the part that writes the tags back to the Google Doc. I have been able to locate the tags but the code doesn't replace them.
Here is what I've written so far.
function mergeApplication() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Merge Data");
var range = sheet.getActiveRange();
var formSheet = ss.getSheetByName("Form Responses");
var lastRow = formSheet.getLastRow();
var lastColumn = sheet.getMaxColumns();
function checkAndComplete() {
var urlColumn = lastColumn;
var checkColumn = (urlColumn - 1);
var checkRange = sheet.getRange(2, checkColumn, (lastRow - 1), 1);
var check = checkRange.getBackgrounds();
var red = "#ff0404";
var yellow = "#ffec0a";
var green = "#3bec3b";
for (var i = 0; i < check.length; i++) {
if (check[i] == green) {
continue;
} else {
var statusCell = sheet.getRange((i+2), checkColumn, 1, 1);
var urlCell = sheet.getRange((i+2), urlColumn, 1, 1);
var dataRow = sheet.getRange((i+2), 1, 1, (lastColumn - 2));
function mergeTasks() {
function docCreator() {
// var templateConditionRange = sheet.getRange((i+2), column);
// var templateConditionCheck = templateConditionRange.getValues();
var docTemplate1 = DriveApp.getFileById(id);
// var docTemplate2 = DriveApp.getFileById(id);
// var docTemplate3 = DriveApp.getFileById(id);
var folderDestination = DriveApp.getFolderById(id);
var clientName = sheet.getRange((i+2), 3).getValue();
var date = sheet.getRange((i+2), 1).getValue();
// if (templateConditionCheck[i] == "") {
var docToUse = docTemplate1;
// }
// if (templateConditionCheck[i] == "") {
// var docToUse = docTemplate2;
// }
// if (templateConditionCheck[i] == "") {
// var docToUse = docTemplate3;
// }
var docName = "Merge Tester Doc for " + clientName + " [" + date + "]";
var docCopy = docToUse.makeCopy(docName, folderDestination);
var docId = docCopy.getId();
var docURL = DriveApp.getFileById(docId).getUrl();
var docToSend = DriveApp.getFileById(docId);
var docBody = DocumentApp.openById(docId).getBody().getText();
function tagReplace() {
var taggedArray = [docBody.match(/\<{2}[\w\d\S]+\>{2}/g)];
var headerArray = [sheet.getRange(1, 1, 1, (lastColumn - 2)).getValues()];
var dataArray = [dataRow.getValues()];
var strippedArray = [];
Logger.log("The preliminary length of taggedArray is " + taggedArray.length);
Logger.log(taggedArray);
function tagStrip() {
for (var t = 0; t < taggedArray.length; t++) {
var strippedString = taggedArray[t].slice(2, -3).toString();
strippedArray.push(strippedString);
Logger.log("The current strippedArray length is " + strippedArray.length);
}
Logger.log("The final strippedArray length is " + strippedArray.length);
Logger.log("The final taggedArray length is " + taggedArray.length);
Logger.log("The final, completed strippedArray is " + strippedArray);
}
function dataMatch() {
for (var s = 0; s < strippedArray.length;) {
for (var h = 0; h < headerArray.length;) {
if (strippedArray[s] == headerArray[h]) {
docBody.replaceText(taggedArray[s].String(), dataArray[h].String());
h=0;
s++;
} else {
h++;
}
}
}
}
tagStrip;
dataMatch;
}
function emailCreator() {
var emailTag = sheet.getRange((i+2), (urlColumn - 2)).getValue();
var emailBody = HtmlService.createHtmlOutputFromFile("Email Template").getContent();
var personalizers = clientName + " [" + date + "]";
var subject = "Merge Tester Email for " + personalizers;
MailApp.sendEmail(emailTag, subject, emailBody, {
name: "Christopher Anderson",
attachments: [docToSend],
html: emailBody,
});
}
tagReplace();
statusCell.setBackground(yellow);
emailCreator();
urlCell.setValue(docURL)
}
statusCell.setBackground(red);
docCreator();
statusCell.setBackground(green);
}
mergeTasks();
}
}
}
checkAndComplete();
}
The problem section is here:
function tagReplace() {
var taggedArray = [docBody.match(/\<{2}[\w\d\S]+\>{2}/g)];
var headerArray = [sheet.getRange(1, 1, 1, (lastColumn - 2)).getValues()];
var dataArray = [dataRow.getValues()];
var strippedArray = new Array();
Logger.log("The preliminary length of taggedArray is " + taggedArray.length);
Logger.log(taggedArray);
function tagStrip() {
for (var t = 0; t < taggedArray.length; t++) {
var strippedString = taggedArray[t].slice(2, -3).toString();
strippedArray.push(strippedString);
Logger.log("The current strippedArray length is " + strippedArray.length);
}
Logger.log("The final strippedArray length is " + strippedArray.length);
Logger.log("The final taggedArray length is " + taggedArray.length);
Logger.log("The final, completed strippedArray is " + strippedArray);
}
function dataMatch() {
for (var s = 0; s < strippedArray.length;) {
for (var h = 0; h < headerArray.length;) {
if (strippedArray[s] == headerArray[h]) {
docBody.replaceText(taggedArray[s].String(), dataArray[h].String());
h=0;
s++;
} else {
h++;
}
}
}
}
tagStrip;
dataMatch;
}
It doesn't even log anything having to do with strippedArray.
It seems to be skipping over that section entirely.
Am I using the correct method of completing this task and/or is there a simpler way of doing it?
It's worth mentioning that my tags in the doc have 2 "<>" around them. That's the reason for my RegEx looking how it does.
Also, when logging the .length of taggedArray, it returns a value of 1.
You never actually call tagStrip which is supposed to work on strippedArray.
You declare it with function tagStrip(){} and later you reference the function with tagStrip; but you never actually call it. The same is happening with dataMatch.
Try calling the two functions by writing
tagStrip();
dataMatch();
If you don't include the parentheses you don't call it you just run the function Objects as statements.
Here is a portion of code I use in my add-on Simply Send, I use the same <<>> merge tags.
//copy template
var mDocDrive = doc.makeCopy(title, folder);
var mDoc = DocumentApp.openById(mDocDrive.getId());
var mDocDriveApp = DriveApp.getFileById(mDoc.getId());
var docToAttach = mDoc.getUrl();
var driveToShare = mDocDriveApp;
// replace text inside template
var body = mDoc.getBody();
body.replaceText("<<SS Title>>", title);
body.replaceText("<<timestamp>>", lastR.timestamp);
body.replaceText("<<username>>", lastR.email);
for (i in lastR.theResponses){
var cur = lastR.theResponses[i];
var name = cur.title;
name = name.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); // this will allow fields that include special characters.
var response = cur.response;
var searchPattern = "<<"+name+">>";
body.replaceText(searchPattern, response);
}
// this will replace any unused tags with nothing.
var ques = getQuestionList();
for (j in ques){
var curq = ques[j].name;
curq = curq.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
var searchPattern2 = "<<"+curq+">>";
body.replaceText(searchPattern2, "");
}
mDoc.saveAndClose();
//create pdf
if (mmDefaults.shareAs == "pdf"){
// uncomment if you want to make the pdf in the merge folder
var asPdf = mDoc.getAs('application/pdf');
asPdf.setName(mDoc.getName()+ ".pdf");
var pdf = DriveApp.createFile(asPdf);
folder.addFile(pdf);
DriveApp.removeFile(pdf);
mDocDriveApp.setTrashed(true);
var docToAttach = pdf;
driveToShare = pdf;
}

Extracting Data from Gmail Message using GAS

I've been working to automatically pull data from an automated Gmail message. There are multiple daily emails that come through with the same label, so ideally I would like to loop through each email, and extract some of the data. I've set it up to use a few regex to grab the data, and it works for the first email. However, it won't loop correctly to find the next email with the label. Here is the code I have so far:
function parseEmailMessages (start) {
var label = GmailApp.getUserLabelByName("Bounce");
var threads = label.getThreads();
var sheet = SpreadsheetApp.getActiveSheet();
var tmp = [];
var messages = GmailApp.getMessagesForThreads(threads);
var bodies = [];
for (var i =0; i < threads.length; i++) {
var bodies = [];
for(k in threads[i].getMessages()) {
bodies.push(threads[i].getMessages()[i].getPlainBody());
var content = bodies.toString();
if (content) {
tmp = content.match(/[\n\r].*First Name\s*:\s*([^\n\r]*)/);
var firstname = (tmp && tmp[1]) ? tmp[1].trim() : 'No username';
tmp = content.match(/[\n\r].*Last Name\s*:\s*([^\n\r]*)/);
var lastname = (tmp && tmp[1]) ? tmp[1].trim() : 'No Lastname';
tmp = content.match(/[\n\r].*Customer ID\s*:\s*([^\n\r]*)/);
var customerID = (tmp) ? tmp[1].trim() : 'No CustomerID';
tmp = content.match(/[\n\r].*Invoice\s*:\s*([^\n\r]*)/);
var invoice = (tmp) ? tmp[1].trim() : 'No Invoice';
sheet.appendRow([firstname, lastname, customerID, invoice]);
Logger.log([firstname,lastname, customerID, invoice]);
}
}
}
};
It loops through correctly the first time, and then gives me an error: TypeError: Cannot call method "getPlainBody" of undefined.
Any help would be greatly appreciated!
You are seeing that error because you should use k variable in the for loop to get each message of that label. Check this line below:
threads[i].getMessages()[k].getPlainBody()
Tried changing this line in the for loop and its working for me.
Hope that helps!
After simplifying my code, I was able to get the script to loop correctly through my emails. This is the code that worked for me:
function processInboxToSheet() {
// Have to get data separate to avoid google app script limit!
//var start = 0;
var label = GmailApp.getUserLabelByName("Bounce");
var threads = label.getThreads();
var sheet = SpreadsheetApp.getActiveSheet();
var result = [];
var newLabel = GmailApp.getUserLabelByName("Done");
var oldLabel = GmailApp.getUserLabelByName("Bounce");
for (var i = 0; i < threads.length; i++) {
var messages = threads[i].getMessages();
var content = messages[0].getPlainBody();
// implement your own parsing rule inside
if (content) {
var tmp;
tmp = content.match(/[\n\r].*First Name\s*:\s*([^\n\r]*)/);
var firstname = (tmp && tmp[1]) ? tmp[1].trim() : 'No username';
tmp = content.match(/[\n\r].*Last Name\s*:\s*([^\n\r]*)/);
var lastname = (tmp && tmp[1]) ? tmp[1].trim() : 'No Lastname';
tmp = content.match(/[\n\r].*Customer ID\s*:\s*([^\n\r]*)/);
var customerID = (tmp) ? tmp[1].trim() : 'No CustomerID';
tmp = content.match(/[\n\r].*Invoice\s*:\s*([^\n\r]*)/);
var invoice = (tmp) ? tmp[1].trim() : 'No Invoice';
sheet.appendRow([firstname, lastname, customerID, invoice]);
}
Utilities.sleep(500);
threads[i].addLabel(newLabel).removeLabel(oldLabel).refresh();
}
};

the difference the regexp result

Why ghi's result is different with abc or def?
abc's result is abc: a-b-c-d-e-f
def's result is def: a-b-c-d-e-f
ghi's result is ghi: a-{1}-c-{3}-e-{5}
What is the reason?
function abc(){
var lang = "{0}-{1}-{2}-{3}-{4}-{5}";
var args = ["a","b","c","d","e","f"];
var exp = /\{(\d+)\}/;
var matches = exp.exec(lang);
while (matches) {
var index = parseInt(matches[1], 10);
lang = lang.replace(matches[0], args[index]);
matches = exp.exec(lang);
}
console.log('abc: ' + lang);
}
abc();
function def(){
var lang = "{0}-{1}-{2}-{3}-{4}-{5}";
var args = ["a","b","c","d","e","f"];
var exp = /\{(\d+)\}/g;
var matches = exp.exec(lang);
while (matches) {
var exp = /\{(\d+)\}/g;
var index = parseInt(matches[1], 10);
lang = lang.replace(matches[0], args[index]);
matches = exp.exec(lang);
}
console.log('def: ' + lang);
}
def();
function ghi(){
var lang = "{0}-{1}-{2}-{3}-{4}-{5}";
var args = ["a","b","c","d","e","f"];
var exp = /\{(\d+)\}/g;
var matches = exp.exec(lang);
while (matches) {
var index = parseInt(matches[1], 10);
lang = lang.replace(matches[0], args[index]);
matches = exp.exec(lang);
}
console.log('ghi: ' + lang);
}
ghi();
Function ghi() needs to reset RegExp object's lastIndex inside the loop:
function ghi(){
var lang = "{0}-{1}-{2}-{3}-{4}-{5}";
var args = ["a","b","c","d","e","f"];
var exp = /\{(\d+)\}/g;
while (matches = exp.exec(lang)) {
var index = parseInt(matches[1], 10);
lang = lang.replace(matches[0], args[index]);
exp.lastIndex = 0;
}
console.log('ghi: ' + lang);
}
Because of exp.lastIndex = 0; call now output will be same.
JavaScript's RegExp object is stateful. When global flag is used, and you call a method the same RegExp object, it will start on the next index from the end of the last match.