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: /Gs|s(?=s*$)/
Advertisement
Answer
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,"_");});