Search code examples
javascriptregextextreplacereplaceall

Replace initial spaces with underscores in Javascript


It's easy to replace spaces with (say) underscores:

y = x.replace(/ /g, '_');

It's also easy to remove leading spaces:

y = x.replace(/^ +/, '');

But is there a good way to replace only the initial spaces with underscores?


Solution

  • I want to replace each of the leading spaces with an underscore

    To do that with just one replace call within the current spec,* you'd need the function call version of replace to do that, creating a string of underscores as long as the matched sequence of spaces:

    y = x.replace(/^ +/, function(m) {
        return "_".repeat(m.length);
    });
    

    or with an ES2015+ arrow function:

    y = x.replace(/^ +/, m => "_".repeat(m.length));
    

    Live Example:

    const x = "    four spaces";
    const y = x.replace(/^ +/, m => "_".repeat(m.length));
    console.log(y);

    String.prototype.repeat was added in ES2015. If you need to support obsolete JavaScript engines, the MDN page has a polyfill you can use.


    * But see ctwheels' answer using a feature from ES2018: Look-behinds. V. clever!