-2

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

gkrogers
  • 7,847
  • 3
  • 28
  • 35
Vinod
  • 30,565
  • 34
  • 92
  • 117
  • 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
  • 12,901
  • 6
  • 35
  • 52
2

in case you did mean Trim:

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

annakata
  • 72,622
  • 16
  • 112
  • 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
  • 27,729
  • 5
  • 65
  • 72