Trimming strings in Javascript

Published:
Updated:
User input plays a big role on webpages. It acts as an interface between users and the server. Handling user inputs is important as we need to ensure what data can be sent to the server and we cannot expect what the user will send. One of the most common things need to be checked is the input strings.

Strings in javascript is not hard but also not easy to be managed. String is an object in javascript and so a lot of methods have been designed to manipulate it but on the other hand, as an input type, it provides the most freedom to users. As a result, checking is also the most complicated with text input type.

This time, we take the start and trailing space in text input as an example. Users, mostly casual ones, sometimes input strings with these whitespaces in the input boxes without caring. It does'nt look much difference in a glance. However, in the server side point of view, these start and trailing space does make a lot difference. For example, for a query request and database update request, these spaces can lead to failure of potential hits in the search and failure in finding the existing database entry. So, removing these starting and trailing space is a very common practice. It can be done on the client side when user submit the data.

Sounds good! Wait! Javascript object does'nt provide the trim function! So, how? Actually, it's not hard to make one trim function by yourself. The following is one of the examples using javascript regular expressions.

 
function trim(str)
{
	var startpatt = /^\s/;
	var endpatt = /\s$/;
	
	while(str.search(startpatt) == 0)
		str = str.substring(1, str.length);
	
	while(str.search(endpatt) == str.length-1)
		str = str.substring(0, str.length-1);	
	
	return str;
}

Open in new window


The function trim() accept a string object and remove any starting and trailing whitespaces (spaces,tabs and newlines) and return the trimmed string. You can use this function to trim form inputs to ensure valid data to be sent.

The following function uses the trim() function and trim all text input of a form
 
function submittrim(form)
{
	for (var i = 0; i<form.elements.length; i++) 
	{
		if(form.elements[i].value != '' && form.elements[i].type == 'text' )
		{
			form.elements[i].value = trim(form.elements[i].value);
		}
	}
	
	return true;
}
</eeSnippet>

And you can trigger the call with the onSubmit event in your form declaration.

[code]
<form method="POST" action="test.do" onsubmit="return submittrim(this);">

Open in new window

0
12,168 Views

Comments (6)

Taking hielo's function, you could just prototype all strings instead.

String.prototype.trim = function()
{
    return this.replace(/^\s+/g, "").replace(/\s+$/g, "");
}
James RodgersWeb Applications Developer
CERTIFIED EXPERT

Commented:
or even

function trim(str) {
      return str.replace(/^\s+|\s+$/g,"");
}

why introduce a loop into a process when there are better methods
CERTIFIED EXPERT

Commented:
All form elements doesn't have a value property, so you should check for the type before you try to access the value:

if (form.elements[i].type == 'text' && form.elements[i].value != '')

Actually, you should rather specify what fields you want to apply trimming to rather than trying to apply it everywhere that it's possible.
function LTrim( value ) { var re = /\s*((\S+\s*)*)/;      return value.replace(re, "$1");      }
      function RTrim( value ) { var re = /((\s*\S+)*)\s*/;      return value.replace(re, "$1");      }
      function trim( value )
      {
            var value = value.replace(/\s\s+/g, ' ');
            return LTrim(RTrim(value));
      }
James RodgersWeb Applications Developer
CERTIFIED EXPERT

Commented:
that is not a trim, that is a white-space replacement and can have unexpected results, for example some writing styles REQUIRE 2 spaces after a period, with your function that would remove, not trim the two spaces resulting in  "This is the end of the sentence.  Followed by another sentence." becoming "This is the end of the sentence.Followed by another sentence." - and actually breaks the writing style completely

View More

Have a question about something in this article? You can receive help directly from the article author. Sign up for a free trial to get started.

Get access with a 7-day free trial.
You Belong in the World's Smartest IT Community