1

Is simple, i have this sentence:

str = "aeiou";

Need RegExp to scan string every X chars, but in reverse.

Example:

let every=2,
    match = new RegExp(/>>RegExp Here<</gi);  
//result "a ei ou"
Arcaela
  • 379
  • 2
  • 11

1 Answers1

2

Use

let str = "Hello world, 13th Mar 2020.";
let every=2;
let rx = new RegExp(`(?=(?:[^]{${every}})+$)`, 'g');
console.log(str.replace(rx, "_"));
// => H_el_lo_ w_or_ld_, _13_th_ M_ar_ 2_02_0.

The regex is /(?=(?:[^]{2})+$)/g, see the regex demo. It matches any location in the string that is followed with one or more repetitions of any two chars up to the string end, and inserts _ at that location.

Details

  • (?= - start of a positive lookahead:
    • (?:[^]{2}) - any char ([^] = [\s\S]), 1 or more times (thanks to +)
    • $ - end of string
  • ) - end of the lookahead.
Wiktor Stribiżew
  • 484,719
  • 26
  • 302
  • 397