jQuery Trim Example
The aim of this example is to show you how to use the jQuery .trim()
method.
Sometimes we need to remove the whitespace (newlines, spaces and tabs) from the beginning and the end of a string. For this purpose we can use jQuery .trim()
method.
If these whitespace characters occur in the middle of the string, they are preserved.
Let’s look at some examples. To download the jQuery library, click here.
1. HTML
First of all you need to create a simple html document.
jQueryTrimExample.html
<!DOCTYPE html> <html> <head> <title>jQuery Trim Example</title> <script src="jquery-2.1.4.min.js"></script> </head> <body> </body> </html>
2. jQuery trim examples
2.1 Trim input value
Let’s add the following simple html code.
User Name :<input type="text" id="name"/><br/> <a href="javascript:return 0;" onclick="showName()">Show Name</a><br/>
In the following jQuery code, the jQuery .trim()
method has been used to trim the input value.
<script type="text/javascript"> function showName() { var name = $("#name").val(); var original = "'"+name+"'"; var trimmed = "'"+$.trim(name)+"'"; alert("original="+original+" , trimmed="+trimmed); } </script>
The result in the browser would be:
2.1 Trim a string
As you can notice in the following example, the jQuery .trim()
method will remove whitespace from the beginning and the end of the string. The whitespaces that reside in the middle of the string will not be removed.
Let’s add the following simple html code.
<h3>Original String</h3> <pre id="original"> Paragraph of text with multiple white spaces before and after. </pre> <br/> <h3>Trimmed String</h3> <pre id="trimmed"></pre> <a href="javascript:return 0;" onclick="trimString()">Trim String</a><br/>
The jQuery .trim()
method has been used to trim the given string.
<script type="text/javascript"> function trimString(){ var myStr = $("#original").text(); var trimStr = $.trim(myStr); $("#trimmed").html(trimStr); } </script>
The result in the browser would be:
Good one.