Home Articles FAQs XREF Games Software Instant Books About Feedback Search Site-Map
irt.org logo

Q1310 How can I trim leading or trailing whitespace/extra spaces?

irt.org | Knowledge Base | JavaScript | Text | Q1310 [ previous next ]

Q1310 How can I trim leading or trailing whitespace/extra spaces?

Try:

<script language="JavaScript"><!--
function trim(strText) { 
    // this will get rid of leading spaces 
    while (strText.substring(0,1) == ' ') 
        strText = strText.substring(1, strText.length);

    // this will get rid of trailing spaces 
    while (strText.substring(strText.length-1,strText.length) == ' ')
        strText = strText.substring(0, strText.length-1);

   return strText;
} 
//--></script>

Dan Hines writes:

I use the following to trim spaces:

<script language="JavaScript"><!--
function trim(str) { 
    str.replace(/^\s*/, '').replace(/\s*$/, ''); 

   return str;
} 
//--></script>

The following was submitted by Jennifer Rahman

This one will actually remove spaces from within the string as well as the beginning and end.

function trim(str) {
  var newstr;
  newstr = str.replace(/^\s*/, "").replace(/\s*$/, ""); 
  newstr = newstr.replace(/\s{2,}/, " "); 
  return newstr;
} 

Feedback on 'Q1310 How can I trim leading or trailing whitespace/extra spaces?'


Provide feedback ...
AddThis Social Bookmark Button

Provide feedback ... AddThis Social Bookmark Button


Last Updated: 30th March 2008. Maintained by: Martin Webb and Michel Plungjan
irt.org liability, trademark, document use, privacy statement and software licensing rules apply.
Copyright © 1996-2008 irt.org, All Rights Reserved.