-2

How to do Trim operation to remove space character in a text field in JavaScript?

gkrogers
  • 8,126
  • 3
  • 29
  • 36
Vinod
  • 31,933
  • 35
  • 96
  • 119
  • Google search for "Javascript trim" gives me 330,000 results in 0.16 seconds. Was that too long a wait for you? – Cerebrus Feb 02 '09 at 09:22

3 Answers3

2

A total dupe of this question:

What is the best way to trim() in javascript

Unless you didn't actually mean trim of course and in fact wanted all the spaces replaced ? In which case you just want:

var myString = "foo bar ddd";
myString = myString.replace(/ /g, "");
Community
  • 1
  • 1
andynormancx
  • 13,421
  • 6
  • 36
  • 52
2

in case you did mean Trim:

x.replace(/^\s*|\s*$/g,'');

annakata
  • 74,572
  • 17
  • 113
  • 180
1

Try this in FF and Chrome

var myString = "                  some text                  ";

alert(myString.trim());

In IE first use this and call like the example above.

// Adding trim function to String object
if(typeof String.prototype.trim !== 'function') {
  String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, '');
  }
}

from here http://goo.gl/L802W

kiranvj
  • 32,342
  • 7
  • 71
  • 76