Wednesday, March 4, 2020

Remove extra spaces from a string

Here is a simple one:

trimmedstr = str.replace(/\s+$/, '');

When you need to remove all spaces at the end:

str.replace(/\s*$/,'');
When you need to remove one space at the end:

str.replace(/\s?$/,'');
\s means not only space but space-like characters; for example tab.

If you use jQuery, you can use the trim function also:

str = $.trim(str);

But trim removes spaces not only at the end of the string, at the beginning also.

 var str  = "Hello World  ";
  var ans = str.replace(/(^[\s]+|[\s]+$)/g, '');

  alert(str.length+" "+ ans.length);

No comments:

Post a Comment

Mixed Content: The page at xxx was loaded over HTTPS, but requested an insecure

 Mixed Content: The page at ' https ://www.test.com/signup.aspx' was loaded over HTTPS, but requested an insecure script ' http ...