Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 803
user1394925 Avatar asked May 25 '12 00:05

user1394925


People also ask

How do you remove the first and last space of a string?

String result = str. trim(); The trim() method will remove both leading and trailing whitespace from a string and return the result.

How can you prevent someone from entering space at the beginning of a textbox?

/^[^\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.

How can remove space from textbox in jQuery?

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.


1 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 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

like image 197
HBP Avatar answered Nov 05 '22 09:11

HBP