skip to Main Content

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


  1. try this and let me know

    let str = 'abcdefgh';
    let result = str.replace(/ab(.)(.)ef(.)(.)/g, 'ab-\U$1$2-ef-$3$4');
    
    Login or Signup to reply.
  2. 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.

    let str = 'abcdefgh';
    let result = str.replace(/(..)(..)(.*)/,
        (m, g1, g2, g3) => g1 + "-" + g2.toUpperCase() + g3.replace(/(..)/g, "-$1"));
    console.log(result);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search