I want to trim any spaces at the start of the text box and trim any spaces at the end of the textbox. So I have found this code on a website which is suppose to remove spaces at the start, end and multiple spaces in between:
function trim(s) {
s = s.replace(/(^\s*)|(\s*$)/gi,"");
s = s.replace(/[ ]{2,}/gi," ");
s = s.replace(/\n /,"\n");
return s;
}
My problem is though that first of all which one of the 3 lines of code is the one where it trims spaces in the middle because I don't need that one. But the main question is how do I get the textbox to access this function?
I tried using onkeypress but this hasn't worked, below is what I have tried:
<p>Search: <input type="text" name="questioncontent" onkeypress="return trim(s)" /></p>
So what I want is that for example if this phrase is entered in textbox ' My Name is Pete '. Then it should remove the spaces at the start and end so it reads 'My Name is Pete'. But how do I get this to work?
UPDATE:
Found out that trim() is jQuery, so does anyone a javascript equivalent for this which can be hand coded to remove spaces at start and end of textbox?
String result = str. trim(); The trim() method will remove both leading and trailing whitespace from a string and return the result.
/^[^\t]. */ checks if the string starts with any character but a space, if you want to exclude all white spaces use /^[^\s]. */ instead. And now add the required and NoWhiteSpaceAtBeginn as class names to the fields you want to validate.
Answer: Use the jQuery $. trim() function You can use the jQuery $. trim() function to remove all the spaces (including non-breaking spaces), newlines, and tabs from the beginning and end of the specified string.
You need to change your HTML :
<p>Search: <input type="text" name="questioncontent" onchange="return trim(this)" /></p>
Pass the input element as a parameter to trim and use onchange instead of onkeypress.
Then trim needs to be :
function trim (el) {
el.value = el.value.
replace (/(^\s*)|(\s*$)/gi, ""). // removes leading and trailing spaces
replace (/[ ]{2,}/gi," "). // replaces multiple spaces with one space
replace (/\n +/,"\n"); // Removes spaces after newlines
return;
}
This modifies the value of the input element, removing leading and trailing spaces, replacing multiple spaces with a single space, and removing any spaces after newline characters.
JSfiddle : http://jsfiddle.net/jstoolsmith/ZNQQm
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With