How to crop space at the beginning and end of a text field?

I want to trim any spaces at the beginning of the text box and trim any spaces at the end of the text box. Therefore, I found this code on a website that is supposed to remove spaces at the beginning, end, and several spaces between them:

function trim(s) {
    s = s.replace(/(^\s*)|(\s*$)/gi,"");
    s = s.replace(/[ ]{2,}/gi," ");
    s = s.replace(/\n /,"\n");
    return s;
}

My problem is that first of all one of the three lines of code is the one where it aligns the spaces in the middle, because I do not need it. But the main question: how to get a text field to access this function?

I tried using onkeypress, but this did not work, below I tried:

<p>Search: <input type="text" name="questioncontent" onkeypress="return trim(s)" /></p>

So, I want, for example, if this phrase is entered in the text box "My Name is Pete". Then he must remove the spaces at the beginning and at the end so that he reads "My Name is Pete". But how do I get this to work?

UPDATE:

Found out that trim () is jQuery, as well as any javascript equivalent for this, which can be manually encoded to remove spaces at the beginning and end of the text field?

+3
source share
3 answers

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 cropping should 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 changes the value of the input element, removing the leading and trailing spaces, replacing multiple spaces with one space, and removing any spaces after newlines.

JSfiddle: http://jsfiddle.net/jstoolsmith/ZNQQm

+7

. , . onkeypress, . , , - , , , .

, , , , .

0
function trim (el) {
    el.value = el.value.
       replace (/(^\s*)|(\s*$)/, ""). // removes leading and trailing spaces
       replace (/[ ]{2,}/gi," ").       // replaces multiple spaces with one space 
       replace (/\n +/,"\n");           // Removes spaces after newlines
    return;
}​
0
source

All Articles