We help IT Professionals succeed at work.

Trim function in JavaScript

Misledman asked
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....
Watch Question

Use regular expressions:

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

If you get any error, try this:

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

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".

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

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.


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

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.