如何在文本框的开头和结尾修剪空格

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

本文关键字:结尾 修剪 空格 开头 文本      更新时间:2023-09-26

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

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

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

我尝试

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

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

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

更新:

发现trim()是jQuery,那么有没有人可以为此编写JavaScript,可以手动编码以删除文本框开头和结尾的空格?

你需要改变你的 HTML :

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

将输入元素作为参数传递以进行修剪并使用 onchange 而不是 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;
}​

这将修改输入元素的值,删除前导空格和尾随空格,用单个空格替换多个空格,并删除换行符后的任何空格。

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

阅读评论.. 这实际上取决于如何使用该功能。 我试图在onkeypress上使用它进行测试,但是没有达到您想要的效果。 然而,我确实得到了与你想要的东西相似的东西,尽管我仍然不确定这是否是你想要的。

我不得不稍微修改函数才能使用您的代码,但基本上,在模糊中,它会执行函数,并相应地更改输入文本。

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