Regex: match and replace two groups at once

Viewed 77

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 class="upper_group">FOO</span>
  • add html tags for lower case groups and transform to uppercase: <span class="lower_group">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 class="bar">$1</span>').replace(/([A-Z'.]+)/g, "<span class='foo'>$1</span>");

Expected output:

<span class="foo">NOCH</span> <span class="foo">KE</span><span class="bar">t</span> <span class="foo">SKUIZ</span><span class="bar">h</span>
4 Answers

You may consider this code:

var s = "NOCH KEt SKUIZh";

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

console.log(r);

//=> '<span class="upper">NOCH</span> <span class="upper">KE</span><span class="lower">t</span> <span class="upper">SKUIZ</span><span class="lower">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

The following assumes your expected output should really be:

<span class="foo">NOCH</span> <span class="foo">KE</span><span class="bar">T</span> <span class="foo">SKUIZ</span><span class="bar">H</span>

You can use a replacer function. For example:

let sentence = "NOCH KEt SKUIZh";

let replacer = (_, g1, g2) =>
  `<span class="${ g1 ? `foo">${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]+).

let sentence = "NOCH KEt SKUIZh";

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

console.log(newSentence);

function getUpperLowerSubstitute(match, upper, lower) {
  return (
    (upper && `<span class="upper_group">${ upper }</span>`) ||
    (lower && `<span class="lower_group">${ 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; }

Related