Skip to content
Advertisement

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: /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,"_");});
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement