Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 721
Marvin Saldinger Avatar asked Feb 18 '23 20:02

Marvin Saldinger


1 Answers

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,"_");});
like image 103
epascarello Avatar answered Feb 21 '23 17:02

epascarello