Marvin Saldinger
Marvin Saldinger

Reputation: 1400

Replace each leading and trailing whitespace with underscore using regex in javascript

var str = '  Some string    ';
var output = str.replace(/^\s|\s(?=\s*$)/g , '_');

The output should look like this

'___Some string____'

This code works fine for the trailing whitespaces but all the leading whitespaces are replaced with just one underscore.

The working php regex for this is: /\G\s|\s(?=\s*$)/

Upvotes: 5

Views: 1085

Answers (4)

hansmaad
hansmaad

Reputation: 18905

With String.prototype.repeat() the accepted answer can now be improved to

function replaceLeadingAndTrailingWhitespace(text, replace) {
    return text.replace(/^\s+|\s+$/g, (spaces) => replace.repeat(spaces.length));
}

Upvotes: 0

Jhankar Mahbub
Jhankar Mahbub

Reputation: 9848

another reg ex

var str = "  asdf       "
str.replace(/^[ ]+|[ ]+$/g,function(spc){return spc.replace(/[ ]/g,"_")})
//"__asdf_______" 

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074485

This works but I don't like it:

var str = "  some string  ";
var result = str.replace(/^\s+|\s+$/g, function(m) {
    return '________________________________________'.substring(0, m.length);
});

Or more flexibly:

var str = "  some string  ";
var result = str.replace(/^\s+|\s+$/g, function(m) {
    var rv = '_',
        n;
    for (n = m.length - 1; n > 0; --n) {
        rv += '_';
    }
    return rv;
});

That can be refined, of course.

But I like epascarello's answer better.

Upvotes: 1

epascarello
epascarello

Reputation: 207521

Not pretty, but gets the job done

var str = "  Some string    ";
var newStr = str.replace(/(^(\s+)|(\s+)$)/g,function(spaces){ return spaces.replace(/\s/g,"_");});

Upvotes: 7

Related Questions