Home > Enterprise >  Regex: match and replace two groups at once
Regex: match and replace two groups at once

Time:01-29

How to find find groups of uppercase and lowercase characters in a string and replace them this way:

  • add html tags for upper case groups: <span >FOO</span>
  • add html tags for lower case groups and transform to uppercase: <span >BAR</span>

I tried this below, but can't transform the lower groups easily to upper case:

let sentence = "NOCH KEt SKUIZh";

let newSentence = sentence.replace(/([a-z] )/g, '<span >$1</span>').replace(/([A-Z'.] )/g, "<span class='foo'>$1</span>");

Expected output:

<span >NOCH</span> <span >KE</span><span >t</span> <span >SKUIZ</span><span >h</span>

CodePudding user response:

let sentence = "NOCH KEt SKUIZh";

let newSentence = sentence.replace(/([a-z] )|([A-Z'.] )/g, (a,b) => b ? `<span >${a.toUpperCase()}</span>` : `<span >${a}</span>`);

console.log(newSentence);

CodePudding user response:

You may consider this code:

var s = "NOCH KEt SKUIZh";

var r = s.replace(/([a-z] )|([A-Z] )/g,
   (m, g1, g2) => '<span >'   g1  : 'upper">'   g2)   '</span>');

console.log(r);

//=> '<span >NOCH</span> <span >KE</span><span >t</span> <span >SKUIZ</span><span >h</span>'

RegEx lamnda Details:

  • ([a-z] ): Matches 1 lowercase letters in in 1st group
  • |: or
  • ([A-Z] ): Matches 1 uppercase letters in in 2nd group
  • (m, g1, g2): Makes available m (full match) and gN (Nth capture group) to lambda expression
  • When g1 is not null then use class lower otherwise use class upper

CodePudding user response:

The following assumes your expected output should really be:

<span >NOCH</span> <span >KE</span><span >T</span> <span >SKUIZ</span><span >H</span>

You can use a replacer function. For example:

let sentence = "NOCH KEt SKUIZh";

let replacer = (_, g1, g2) =>
  `<span >${g1}` : `bar">${g2.toUpperCase()}` }</span>`;

let newSentence = sentence.replace(/([A-Z] )|([a-z] )/g, replacer);

console.log(newSentence);

The g1 is the string captured by the ([A-Z] ) and the g2 is the string captured by the ([a-z] ).

CodePudding user response:

function getUpperLowerSubstitute(match, upper, lower) {
  return (
    (upper && `<span >${ upper }</span>`) ||
    (lower && `<span >${ lower }</span>`) ||
    ''
  );
}
const regXUpperLower = /(?<upper>[[A-Z] )|(?<lower>[[a-z] )/g

console.log(
  '"NOCH KEt SKUIZh".replace(regXUpperLower, getUpperLowerSubstitute) ...',
  "NOCH KEt SKUIZh".replace(regXUpperLower, getUpperLowerSubstitute)
);
.as-console-wrapper { min-height: 100%!important; top: 0; }

  •  Tags:  
  • Related