How to replace found regex sub string with spaces with equal length in javascript?

In javascript if I have something like

string.replace(new RegExp(regex, "ig"), " ")

this replaces all found regexes with a single space. But how would I do it if I wanted to replace all found regexes with spaces that matched in length?

so if regex was \d+, and the string was


it changes to

"   hello    "


3 answers

  • answered 2017-12-06 01:33 niee

    "123hello4567".replace(new RegExp(/[\d]/, "ig"), " ")
    1 => " "
    2 => " "
    3 => " "
    "   hello    "
    "123hello4567".replace(new RegExp(/[\d]+/, "ig"), " ")
    123 => " "
    4567 => " "
    " hello "

  • answered 2017-12-06 01:34 packmul3

    If you just want to replace every digit with a space, keep it simple:

    var str = "123hello4567";
    var res = str.replace(/\d/g,' ');
    "   hello    "

    This answers your example, but not exactly your question. What if the regex could match on different numbers of spaces depending on the string, or it isn't as simple as /d more than once? You could do something like this:

    var str = "123hello456789goodbye12and456hello12345678again123";
    var regex = /(\d+)/;
    var match = regex.exec(str);
    while (match != null) {
        // Create string of spaces of same length
        var replaceSpaces = match[0].replace(/./g,' ');  
        str = str.replace(regex, replaceSpaces);
        match = regex.exec(str);
    "   hello      goodbye  and   hello        again   "

    Which will loop through executing the regex (instead of using /g for global).

    Performance wise this could likely be sped up by creating a new string of spaces with the length the same length as match[0]. This would remove the regex replace within the loop. If performance isn't a high priority, this should work fine.

  • answered 2017-12-06 01:59 Jaromanda X

    The replacement argument (2nd) to .replace can be a function - this function is called in turn with every matching part as the first argument

    knowing the length of the matching part, you can return the same number of spaces as the replacement value

    In the code below I use . as a replacement value to easily illustrate the code

    Note: this uses String#repeat, which is not available in IE11 (but then, neither are arrow functions) but you can always use a polyfill and a transpiler

    let regex = "\\d+";
    console.log("123hello4567".replace(new RegExp(regex, "ig"), m => '.'.repeat(m.length)));

    Internet Exploder friendly version

    var regex = "\\d+";
    console.log("123hello4567".replace(new RegExp(regex, "ig"), function (m) {
        return Array(m.length+1).join('.');

    thanks to @nnnnnn for the shorter IE friendly version