Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Javascript code for trim spaces

Status
Not open for further replies.

gagandeepbedi

Technical User
Feb 21, 2002
1
US
I have First Name and Last Name in the same input box and I am looking for the javascript code that would trim any extra spaces between the first and the last name, before the first name and after the last name.
 
Javascript doesnt have trim function like other programming languages,U will have to write one by yourself.

The logic would be to take the string and loop through its length.check if each character is " "(space) and replace that character with "".Hope that helps Badrinath Chebbi
 
Chebbi's suggestion will remove any and all spaces within the input value. If you want simply to remove all extra spaces (Yes, you did say that, I think), here's a simple function:
Code:
function inputWSpace(myInput) {
 myInput.value=myInput.value.replace(/(\s)\s+/, "$1").replace(/^\s*/, "").replace(/\s*$/, "");
}
Code:
myInput
is the particular
Code:
input
that needs its value to be changed. Here's an example of how you would use the function:
Code:
<form>
 <input type=&quot;text&quot; ondblclick=&quot;inputWSpace(this)&quot;>
</form>
[code]
After entering text into the above [code]input
, if you double-click it, its value will contain:

No spaces before the text.
No spaces after the text.
Single-spaces between words.


I hope you find what you're looking for.
bluebrain.gif
blueuniment.gif
 
Here's a correction for function
Code:
inputWSpace
:
Code:
function inputWSpace(myInput) {
 myInput.value=myInput.value.replace(/(\s)\s+/g, &quot;$1&quot;).replace(/^\s*/, &quot;&quot;).replace(/\s*$/, &quot;&quot;);
}

The difference is, with the single added character, you can do multiple formatting sequences. So, in other words, the last time I posted I made a boo-boo because I forgot a character. Use this code instead.
bluebrain.gif
blueuniment.gif
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top