There are many ways you can do this, but I find it easiest to understand with three individual replacements:
function cleanup( str ) {
return str
.replace( / +/g, ' ' )
.replace( /^ /, '' )
.replace( / $/, '' );
}
console.log(
"'" +
cleanup( " My name is Eddy " ) +
"'"
);
Logs:
'My name is Eddy'
This is compatible with very old browsers as well as new ones.
Edit: So you want to remove all leading spaces, but if there are trailing spaces you want to keep one trailing space, is that right? That's not how you described the problem.
If you look at the cleanup function I posted, it should be apparent how to fix it to not remove trailing spaces:
function cleanup( str ) {
return str
.replace( / +/g, ' ' )
.replace( /^ /, '' );
}
console.log(
"'" +
cleanup( " My name is Eddy " ) +
"'"
);
Logs:
'My name is Eddy '
Eddynot removed in the first example?