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

How to exclude lowercase string in replace RegEx?

i have code like this, and i want to exclude lowercase word from RegEx replace?

let str = "a A am Am a# A# a#d A#d";
 let obj = {
     'A': 'a-uppercase',
     'Am': 'a-minor',
     'A#': 'a-hasgtag',
     'A#d': 'a-minor-d',
 };
 
 function allReplace(par_one, par_two) {
            for (const x in obj) {
                let rx = new RegExp(
                    "(^|\\s)" + x.replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&") + "(?!\\S)",
                    "gi"
                );
                console.log(obj[x]);
                str = str.replace(rx, "$1" + obj[x]);
            }
            return str;
        }

console.log(allReplace(str, obj));

when i console log:

a-uppercase a-uppercase a-minor a-minor a-hasgtag a-hasgtag a-minor-d a-minor-d

my expectation console log is:

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

a a-uppercase am a-minor a# a-hasgtag a#d a-hasgtag-d

how can i do from this?

>Solution :

remove the "i" flag from the RegExp, make the matches case-sensitive

let str = "a A am Am a# A# a#d A#d";

let obj = {
    'A': 'a-uppercase',
    'Am': 'a-minor',
    'A#': 'a-hasgtag',
    'A#d': 'a-minor-d',
};

function allReplace(par_one, par_two) {
    for (const x in obj) {
        let rx = new RegExp(
            "(^|\\s)" + x.replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&") + "(?=\\s|$)",
            "g"
        );
        str = str.replace(rx, (match, p1) => {
            return match.charAt(0) === match.charAt(0).toUpperCase() ? p1 + obj[x] : match;
        });
    }
    return str;
}

console.log(allReplace(str, obj));
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