I needed to trim a string and also replace more than one spaces with a single space. The solution was simple with String.replace in JavaScript. Here's the code:
Making a function out of it.
Code: JavaScript
var m = " My name is Pradeep ";
m = m.replace(/^[\s]+/,'').replace(/[\s]+$/,'').replace(/[\s]{2,}/,' ');
Code: JavaScript
function trim(str)
{
if(!str || typeof str != 'string')
return null;
return str.replace(/^[\s]+/,'').replace(/[\s]+$/,'').replace(/[\s]{2,}/,' ');
}

