Reputation: 1400
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
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
Reputation: 9848
another reg ex
var str = " asdf "
str.replace(/^[ ]+|[ ]+$/g,function(spc){return spc.replace(/[ ]/g,"_")})
//"__asdf_______"
Upvotes: 0
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
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