0

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.

1 Answer 1

1

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" + ']"'))

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.