Just launched the new site! Please excuse the mess as it is set up. Jump to: main content, navigation or the bottom.

The trim function

The function makes 3 regular expression calls to remove spaces at the start, the end and any multiple spaces.

// remove multiple, leading or trailing spaces
function trim(s) {
	s = s.replace(/(^\s*)|(\s*$)/gi,"");
	s = s.replace(/[ ]{2,}/gi," ");
	s = s.replace(/\n /,"\n");
	return s;
}

To use it, do something like this:-

alert(trim(" My name is stewart "));

It will strip the spaces at the start, end and also any multiple spaces in the middle to give a nicely formatted string! Simple, eh?


Comments (6)

What others have said about this post.

Got something to say?

Join the discussion! You know how these things work; enter your details and comments below and be heard.

If you have trouble reading the code, click on the code itself to generate a new random code.

Going up? Back to the top