jQuery删除input propertychange上的第一个和最后一个空格

时间:2017-01-25 06:00:12

标签: jquery client-side-validation

我想删除所有事件(keyup / keydown / oncopy / onpaste等)上任何输入的第一个和最后一个空格。

我尝试使用以下代码,但它无效。

SELECT room_id
FROM allotment
WHERE date >= '2017-01-28' 
  AND date <= '2017-01-31'
group by room_id
having sum(is_closed = 1) = 0

3 个答案:

答案 0 :(得分:2)

也许trim()是您正在寻找的内容: https://api.jquery.com/jQuery.trim/

答案 1 :(得分:2)

您需要更改HTML:

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;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Enter value : <input type="text" name="test_input" onchange="return trim(this)" />

请检查我上面的代码段吗?

答案 2 :(得分:0)

你应该使用jquery的trim()函数,这对删除第一个和最后一个空格很有用。您可以从https://api.jquery.com/jQuery.trim/获得更多想法。

e.g。 $.trim(" hello, how are you? ");为您提供"hello, how are you?"输出。