Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Replace specific group of characters in match using regex

So I want to match in string bellow, which will be formula for excell/ spreadsheet type cell, all addresses: \w+\d+ , and change numbers only number part in them. I want to get following strings from original: "= A2 + B2", "=A3+B3", "=A4+B4" ...

I tried:

const a = "=A1 + B1"
for (let i = 0; i < 100 ; i++) {
    const b = a.replace(/\w+$(\d+)/g, String(i + 1));
    console.log(b)
}
    

and it gives result:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

enter image description here

then if I do without $ before grouping () parentesis:

const a = "=A1 + B1"
for (let i = 0; i < 100 ; i++) {
    const b = a.replace(/\w+(\d+)/g, String(i + 1));
    console.log(b)
}

I get:

enter image description here

>Solution :

Something like this?

const a = "=A1 + B1"
for (let i = 0; i < 10 ; i++) {
    const b = a.replace(/\b\w+\d+\b/g, function(match) {
        const num = match.match(/\d+/);
        const newNum = Number(num[0]) + i;
        return match.replace(/\d+/, newNum);
    });
    console.log(b);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading