<

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x

Trimming strings in Javascript

Published on
14,973 Points
11,973 Views
Last Modified:
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
Comment
Author:quincydude
6 Comments
LVL 82

Expert Comment

by:hielo
why not simply:

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

Expert Comment

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

String.prototype.trim = function()
{
    return this.replace(/^\s+/g, "").replace(/\s+$/g, "");
}
0
LVL 25

Expert Comment

by:James Rodgers
or even

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

why introduce a loop into a process when there are better methods
0
Determine the Perfect Price for Your IT Services

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden with our free interactive tool and use it to determine the right price for your IT services. Download your free eBook now!

LVL 29

Expert Comment

by:Göran Andersson
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.
0
LVL 7

Expert Comment

by:Atique Ansari
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));
      }
0
LVL 25

Expert Comment

by:James Rodgers
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
0

Featured Post

Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

Join & Write a Comment

The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

Keep in touch with Experts Exchange

Tech news and trends delivered to your inbox every month