如何修剪文本框开头和结尾的空格? [英] How to trim a space at the start and end of textbox?

查看:103
本文介绍了如何修剪文本框开头和结尾的空格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想修剪文本框开头的任何空格,并修剪文本框末尾的任何空格。所以我在一个网站上发现了这个代码,它假设在开头,结尾和中间的多个空格中删除空格:

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

我的问题是,首先是3行代码中的哪一行它是在中间修剪空间的那个,因为我不需要那个。但主要问题是我如何让文本框访问此功能?

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?

我尝试使用onkeypress但这没有用,下面是我尝试过的:

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>

所以我想要的是,例如,如果在文本框中输入此短语我的名字是Pete 。然后它应该删除开头和结尾的空格,使其显示为我的名字是皮特。但是我如何让它发挥作用?

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?

更新:

发现trim()是jQuery,所以有人为此javascript等效于此可以手动编码以删除文本框开头和结尾的空格?

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?

推荐答案

您需要更改HTML:

<p>Search: <input type="text" name="questioncontent" onchange="return trim(this)" /></p>​

将输入元素作为参数传递给trim并使用onchange而不是onkeypress。

Pass the input element as a parameter to trim and use onchange instead of onkeypress.

然后需要修剪:

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

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

这篇关于如何修剪文本框开头和结尾的空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆