Trimming strings in Javascript

AID: 191
  • Status: Published

5500 points

  • Byquincydude
  • TypeGeneral
  • Posted on2008-11-20 at 16:52:42
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;
}
                                    
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:

Select allOpen 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);">
                                    
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:

Select allOpen in new window

Asked On
2008-11-20 at 16:52:42ID191
Tags

Trimming

,

trim

,

strings

,

Javascript

Topic

JavaScript

Views
7865

Comments

Expert Comment

by: hielo on 2008-11-20 at 18:26:53ID: 366

why not simply:

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

Expert Comment

by: Morcalavin on 2008-11-21 at 04:52:00ID: 381

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

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

Expert Comment

by: Jester_48 on 2008-11-21 at 05:41:44ID: 382

or even

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

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

Expert Comment

by: GreenGhost on 2008-11-21 at 21:10:14ID: 399

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.

Expert Comment

by: atique_ansari on 2012-03-28 at 02:33:00ID: 47659

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));
      }

Expert Comment

by: Jester_48 on 2012-03-28 at 07:21:10ID: 47688

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

Add your Comment

Please Sign up or Log in to comment on this article.

Join Experts Exchange Today

Gain Access to all our Tech Resources

Get personalized answers

Ask unlimited questions

Access Proven Solutions

Search 3.2 million solutions

Read In-Depth How-To Guides

1000+ articles, demos, & tips

Watch Step by Step Tutorials

Learn direct from top tech pros

And Much More!

Your complete tech resource

See Plans and Pricing

30-day free trial. Register in 60 seconds.

Loading Advertisement...

Top JavaScript Experts

  1. leakim971

    511,289

    Sage

    2,168 points yesterday

    Profile
    Rank: Genius
  2. mplungjan

    291,279

    Guru

    2,800 points yesterday

    Profile
    Rank: Savant
  3. nap0leon

    195,491

    Guru

    0 points yesterday

    Profile
    Rank: Sage
  4. Proculopsis

    182,948

    Guru

    0 points yesterday

    Profile
    Rank: Sage
  5. COBOLdinosaur

    157,309

    Guru

    0 points yesterday

    Profile
    Rank: Genius
  6. chaituu

    130,684

    Master

    0 points yesterday

    Profile
    Rank: Sage
  7. Ray_Paseur

    130,217

    Master

    330 points yesterday

    Profile
    Rank: Savant
  8. tommyBoy

    125,345

    Master

    0 points yesterday

    Profile
    Rank: Genius
  9. StingRaY

    114,318

    Master

    0 points yesterday

    Profile
    Rank: Wizard
  10. DaveBaldwin

    80,081

    Master

    336 points yesterday

    Profile
    Rank: Genius
  11. ansudhindra

    79,054

    Master

    2,000 points yesterday

    Profile
    Rank: Wizard
  12. ChrisStanyon

    62,768

    Master

    800 points yesterday

    Profile
    Rank: Sage
  13. hielo

    61,266

    Master

    0 points yesterday

    Profile
    Rank: Savant
  14. HainKurt

    59,030

    Master

    0 points yesterday

    Profile
    Rank: Genius
  15. BuggyCoder

    54,739

    Master

    0 points yesterday

    Profile
    Rank: Sage
  16. mroonal

    54,339

    Master

    10 points yesterday

    Profile
    Rank: Sage
  17. tagit

    54,093

    Master

    1,600 points yesterday

    Profile
    Rank: Genius
  18. gurvinder372

    52,824

    Master

    10 points yesterday

    Profile
    Rank: Genius
  19. basicinstinct

    52,586

    Master

    0 points yesterday

    Profile
    Rank: Genius
  20. JonNorman

    45,158

    2,200 points yesterday

    Profile
    Rank: Master
  21. Lalit-Chandra

    44,420

    0 points yesterday

    Profile
    Rank: Master
  22. xmediaman

    36,450

    3,800 points yesterday

    Profile
    Rank: Guru
  23. kozaiwaniec

    33,100

    0 points yesterday

    Profile
    Rank: Guru
  24. Kravimir

    32,700

    0 points yesterday

    Profile
    Rank: Genius
  25. designatedinitializer

    32,300

    0 points yesterday

    Profile
    Rank: Master

Hall Of Fame