I want to replace some character in a string to uppercase with javascript like below.
source: "abcdefgh"
expect: "ab-CD-ef-gh"
my method is:
let str = 'abcdefgh';
let result = str.replace(/ab(.*)ef(.*)/g, (...args) => `ab-${args[1].toUpperCase()}-ef-${args[2]}`);
console.log(result);
but I try to find a pure regular expression way to do it.
the code is like this:
let str = 'abcdefgh';
let result = str.replace(/ab(.*)ef(.*)/g, 'ab-\L$1-ef-$2'));
console.log(result);
the result is
ab-Lcd-ef-gh
seems not work.
please help, thanks
2
Answers
try this and let me know
JavaScript’s regex engine does not natively support upper or lower casing the replacement. In JS your first attempt of using a function in the replacement is the correct approach.