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*$)/
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,"_");});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With