简体   繁体   English

JS/JQuery - 如果它是第一个和/或最后一个字符,则从输入字段中删除空格

[英]JS/JQuery - Remove space from input field if it is the first and/or last character

I have a site search (using Examine & Razor) that breaks if a space character is the first or last (or both) character in a search query.我有一个站点搜索(使用 Examine & Razor),如果空格字符是搜索查询中的第一个或最后一个(或两个)字符,该搜索就会中断。 For example "hello" & "hello world" both work fine, but " hello" & "hello " don't.例如,“hello”和“hello world”都可以正常工作,但“hello”和“hello”却不行。 Is it possible to remove any spaces such as these before the input field is submitted using JS/JQuery?是否可以在使用 JS/JQuery 提交输入字段之前删除诸如此类的任何空格?

I think what you want is JQuery.trim()我想你想要的是 JQuery.trim()

http://api.jquery.com/jQuery.trim/ http://api.jquery.com/jQuery.trim/

Try using this regular expression for your search strings:尝试将此正则表达式用于您的搜索字符串:

// presume searchStr = '" hello"' or '"hello "' or '" hello world   "'
searchStr.replace(/(")\s+|\s+(")/g,'"'); //=> "hello" or "hello world"

Considering the answer of your choice, the quaotation marks ( " ) are not included? In that case trim would be sufficient. In non jquery script:考虑到您选择的答案,不包括引号 ( " )?在这种情况下, trim就足够了。在非 jquery 脚本中:

searchStr.replace(/^\s+|\s+$/g,'');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM