0

Here I need to replace #tenant_id# in multiple files the input is coming from an json object as 1.

This is the first file to replace #tenant_id#:

INSERT INTO mst_designation (designation_name,tenant_id)
SELECT designation_name,#tenant_id# tenant_id FROM mst_designation  mdes
WHERE tenant_id = -1 
AND NOT EXISTS (SELECT 1 FROM mst_designation 
WHERE designation_name = mdes.designation_name AND tenant_id = #tenant_id#);

Here first #tenant_id# is replaced into 1 and second one is not replacing

The code for replacing string :

  const dirPath = path.join(__dirname + '/script/')

  filenames = fs.readdirSync(dirPath)

  filenames.forEach(files => {
            file = fs.readFileSync(dirPath + files, { encoding: 'utf8', flag: 'r' })

            fileReplace = file.replace("#tenant_id#", new_tenant_id)
            logger.log('silly', 'tenantOnBoard : tenant_id replace : Start ' + fileReplace);

             const queryCreateTenant = conPool.query(fileReplace)
             console.log(queryCreateTenant);
}

This is the code for replacing the string and here op is coming as

INSERT INTO mst_designation (designation_nametenant_id)
SELECT designation_name,#tenant_id# tenant_idFROM mst_designation  mdes
WHERE tenant_id = -1 
AND NOT EXISTS (SELECT 1 FROM mst_designation 
WHERE designation_name = mdes.designation_name AND tenant_id = #tenant_id#);

the #tenant_id# is not replacing on 2nd place How to resolve this issue

Rahman Haroon
  • 1,088
  • 2
  • 12
  • 36
  • Does this answer your question? [How to replace all occurrences of a string?](https://stackoverflow.com/questions/1144783/how-to-replace-all-occurrences-of-a-string) – Dane Brouwer Nov 23 '20 at 12:38

2 Answers2

1

This is expected behavior in javascript. To replace a string multiple times you may use RegExp with g flag:

fileReplace = file.replace(/#tenant_id#/g, new_tenant_id)
1

You have to use replaceAll().

var query = "INSERT INTO mst_designation (designation_name,tenant_id) "+
"SELECT designation_name,#tenant_id# tenant_id FROM mst_designation  mdes "+
"WHERE tenant_id = -1 AND NOT EXISTS (SELECT 1 FROM mst_designation WHERE designation_name = "+ " mdes.designation_name AND tenant_id = #tenant_id#);"

var fileReplace = query.replaceAll("#tenant_id#", "new_replaced_id")

console.log(fileReplace)

The name is self-explanatory. Using replaceAll() you will replace all instances that match insetad of only the first one.

J.F.
  • 13,927
  • 9
  • 27
  • 65