jQuery

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:

Trim input value
Trim input value

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:

Trim a string in jquery
Trim a string in jquery

3. Download the source code

Download: You can download the full source code of this example here: jQuery Trim example

Saeb Najim

Saeb has graduated from the University of Technology. During the last ten years (since 2005) he has been involved with a large number of projects about programming, software engineering, design and analysis . He works as a senior Software Engineer in the e-commerce and web development sector where he is mainly responsible for projects based on Java, Java frameworks, design patterns and Big Data technologies.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
omid nasri
8 years ago

Good one.

Back to top button