Taking out white space in string

A

Ashlie

I am trying to develop a script that takes out the white space at the
FRONT and the BACK of a string but not the middle. I have a string
that looks like this:

XXXX XXXX XXXX XXXX

The groupings within the string can be any length...however, in order
to dump this data into a SQL database, the potential added white space
at the front or the back of the string needs to be deleted as the user
moves from one text box in a form to the next.

Any ideas?
 
D

Douglas Crockford

I am trying to develop a script that takes out the white space at the
FRONT and the BACK of a string but not the middle. I have a string
that looks like this:

XXXX XXXX XXXX XXXX

The groupings within the string can be any length...however, in order
to dump this data into a SQL database, the potential added white space
at the front or the back of the string needs to be deleted as the user
moves from one text box in a form to the next.

Check out the trim method here:
http://www.crockford.com/javascript/remedial.html
 
E

Evertjan.

Ashlie wrote on 08 jul 2003 in comp.lang.javascript:
I am trying to develop a script that takes out the white space at the
FRONT and the BACK of a string but not the middle. I have a string
that looks like this:

XXXX XXXX XXXX XXXX

The groupings within the string can be any length...however, in order
to dump this data into a SQL database, the potential added white space
at the front or the back of the string needs to be deleted as the user
moves from one text box in a form to the next.


<script>
function trim(s){
return s.replace(/^\s*(.*?)\s*$/,"$1")
}

alert(">"+trim(' XXXX XXXX XXXX XXXX ')+"<")
</script>
 
F

frogcoder

This works fine for me,

trim(stringValue)
{
return stringValue.replace(/(^\s*|\s*$)/, "");
}
 
L

Lasse Reichstein Nielsen

Please don't top post.
This works fine for me,

trim(stringValue)
{
return stringValue.replace(/(^\s*|\s*$)/, "");
}

Does it now?
What is the result of
trim(" foo bar ")
?
It only removes whitespace before *or* after the string, not both.
It can be fixed simply by adding a "g" after the regexp:
/(^\s+|\s+$)/g
(uses + too, there is no reason to replace nothing)

/L
 
D

Dr John Stockton

JRS: In article <[email protected]>, seen in
news:comp.lang.javascript said:
This works fine for me,

trim(stringValue)
{
return stringValue.replace(/(^\s*|\s*$)/, "");
}

See FAQ sec 4.16 for a correct way of removing both leading & trailing
white-space.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,540
Members
45,024
Latest member
ARDU_PROgrammER

Latest Threads

Top