user1394925
user1394925

Reputation: 752

How to trim a space at the start and end of textbox?

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?

Upvotes: 5

Views: 21398

Answers (3)

bharati
bharati

Reputation: 1

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;
}​

Upvotes: 0

HBP
HBP

Reputation: 16063

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

Upvotes: 12

Daedalus
Daedalus

Reputation: 7722

Reading the comments.. it really depends on how the function is used. I attempted to test with it on onkeypress, however that didn't have your desired effect. I did however get something similar to what you desired, though I'm still unsure if that's what you wanted.

I had to modify the function slightly to work with your code, but basically, on blur, it executes the function, and alters the input text accordingly.

Upvotes: 0

Related Questions