Adatix
Adatix

Reputation: 11

Javascript Replace with loop / recursive for this situation

I am working on a string which is like (this is really long string with 500 + values, which would run incrementally as shown in this example. )

Select "start_date", "pmcounter"[1] as "pmcounter[1]", "pmcounter"[2] as "pmcounter[2]" ,"pmcounter"[31] as "pmcounter[31]" from view

I want this string to look like

Select "start_date", "pmcounter"[1] as "pmcounter_1", "pmcounter"[2] as "pmcounter_2" ,"pmcounter"[31] as "pmcounter_31" from view

For which I have done this code. (I am very much at beginner level, you can see that with my code :) )

var fields = "Select \"start_date\", \"pmcounter\"[1] as \"pmcounter[1]\", \"pmcounter\"[2] as \"pmcounter[2]\" ,\"pmcounter\"[31] as \"pmcounter[31]\" from view";

fields = fields.replace(/\[1\]\"/,'_1\"')
fields = fields.replace(/\[2\]\"/,'_2\"')
fields = fields.replace(/\[3\]\"/,'_3\"')
fields = fields.replace(/\[31\]\"/,'_31\"')
// const regex = new RegExp("ReGeX"+n+"ReGeX");
console.log(fields);

Output:

Select "start_date", "pmcounter"[1] as "pmcounter_1", "pmcounter"[2] as "pmcounter_2" ,"pmcounter"[31] as "pmcounter_31" from view

Can you please tell me an easy way to do it. Some For loop.

Upvotes: 0

Views: 49

Answers (1)

Code Maniac
Code Maniac

Reputation: 37755

You can use captured group and while replacing use back reference

\[(\d+)\]"
  ^^^^^
    --------- Capture group, which we are referencing by `$1` in replace callback

const fields = "Select \"start_date\", \"pmcounter\"[1] as \"pmcounter[1]\", \"pmcounter\"[2] as \"pmcounter[2]\" ,\"pmcounter\"[31] as \"pmcounter[31]\" from view";

console.log(fields.replace(/\[(\d+)\]"/g, '_[' + "$1" + ']"'))

Upvotes: 1

Related Questions