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="text" ondblclick="inputWSpace(this)">
</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.
function inputWSpace(myInput) {
myInput.value=myInput.value.replace(/(\s)\s+/g, "$1").replace(/^\s*/, "").replace(/\s*$/, "");
}
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.
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.