71

jQuery trim not working. I wrote the following command to remove white space. Whats wrong in it?

var str = $('input').val();

str = jquery.trim(str);
console.log(str);

Fiddle example.

Vaidas
  • 968
  • 9
  • 22
Akhil K Nambiar
  • 3,835
  • 13
  • 47
  • 85

5 Answers5

120

jQuery.trim() capital Q?

or $.trim()

Edit (2021): This answer is 11 years old (2010). There are better solutions posted below.

Jason
  • 3,357
  • 1
  • 22
  • 29
  • 7
    JavaScript *does* have a native `.trim()` method - http://stackoverflow.com/questions/4040259/trim-to-remove-white-space/28017159#28017159 – Josh Crozier Jan 19 '15 at 02:32
  • Thank you for this tip, sir :) – Nekto Mar 17 '17 at 13:12
  • 1
    **2020 Update**: as of [jQuery v3.5.0](https://blog.jquery.com/2020/04/10/jquery-3-5-0-released/) , `$.trim(mystr)` is deprecated. Use JS native `mystr.trim()`. – evilReiko Jul 11 '21 at 09:57
71

No need for jQuery

JavaScript does have a native .trim() method.

var name = "    John Smith  ";
name = name.trim();

console.log(name); // "John Smith"

Example Here

String.prototype.trim()

The trim() method removes whitespace from both ends of a string. Whitespace in this context is all the whitespace characters (space, tab, no-break space, etc.) and all the line terminator characters (LF, CR, etc.).

Community
  • 1
  • 1
Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
  • Nice. Thanks Josh – Darós Nov 07 '17 at 17:11
  • 1
    Keep in mind that these methods don't work exactly the same with different types of values, e.g. calling `$.trim(undefinedVariable)` will result in empty string, but calling `undefinedVariable.trim()` will cause TypeError – Krzysztof Grzybek Jun 07 '18 at 08:02
11

or just use $.trim(str)

Moin Zaman
  • 25,281
  • 6
  • 70
  • 74
9

Why not try this?

html:

<p>
  a b c
</p>

js:

$("p").text().trim();
macio.Jun
  • 9,647
  • 1
  • 45
  • 41
2

Try this

  $('input').val($('input').val().trim());
Joukhar
  • 724
  • 1
  • 3
  • 18
  • Your answer could be improved by adding more information on what the code does and how it helps the OP. – Tyler2P Apr 22 '22 at 18:30