Search code examples
javascriptregexstringreplacewhitespace

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*$)/


Solution

  • 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,"_");});