// Declare string with spaces on both ends:
var str = " I learn JavaScript ";
// "g" = global: replace *all* leading spaces with empty string
str = str.replace( /^\s+/g, "" );
// Surround with square brackets to clearly show spaces
alert( "[" + str + "]" );
Note: we could have used a space character as pattern, but wouldn't have removed tabs, blank new lines, etc. The "\s" pattern (lowercase "s") matches *all* white space.
var str = " I learn JavaScript "; // one trailing leading space
// Explicitly assign the result to modify the original string:
str = str.replace( /\s+$/g, "" );
alert( "[" + str + "]" );
var str = " I learn JavaScript ";
// Pipe character means "this pattern or that pattern"
str = str.replace( /^\s+|\s+$/g, "" );
alert( "[" + str + "]" );