Home Articles FAQs XREF Games Software Instant Books BBS About FOLDOC RFCs Feedback Sitemap
irt.Org
#

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

You are here: irt.org | FAQ | JavaScript | Text | Q1310 [ previous next ]

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?'

©2018 Martin Webb