We help IT Professionals succeed at work.

Trim function in JavaScript

Misledman
Misledman asked
on
In VB there is a Trim function that strips leading and trailing spaces. How do I do it in Javascript. The goal is to insure that they have put something in a text box before I allow submitting the form.

I used txtObject.Replace(text, " " , ""). That only got rid of the first space. Not all 5 spaces in a row....
Comment
Watch Question

Commented:
Use regular expressions:

strNew = origStr.replace(/(^ *| *$)/g, "");

If you get any error, try this:

strNew = origStr.replace(/^ */, "");
strNew = strNew.replace(/ *$/, "");

Enjoy!
You might want to do this (just to be more precise):
replace(/ *$/, "");
change to
replace(/\s*$/, ""); or replace(/\S*$/, "");
I forget if the capital or lowe-case "S" means "all whitespace", or "all non-white space".


Commented:
Even more precise... The \s (lowercase) explicitly matches any white spaces: space, tab, form feed, etc.
:-D

Commented:
I'm surprised there isn't a "trim" function in JavaScript. You can also do this...

Place the following in a .js file...one where you keep all your strings utils maybe.

//==//strutils.js//==//

function trimString (str) {
  str = this != window? this : str;
  return str.replace(/^\s+/g, '').replace(/\s+$/g, '');
}

String.prototype.trim = trimString;

//==//end file//==//

You can then call "trim" as follows:

var s = '  jan  ';
s = s.trim();
alert(s.length);

Commented:
I belive that you have rescived your answer.
It's time to close your question Misledman!

Explore More ContentExplore courses, solutions, and other research materials related to this topic.