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:
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));