javascript 删除javascript字符串前后的多余空格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23484876/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove Extra Spaces Before and After javascript string
提问by user3135730
var $one = $('#oneClueShow');
var x = $("#clueOneInput").find('input[type=text]').val();
if(x == 'D R' || x == 'd r'|| x == 'D r'|| x == 'd R'|| x == 'd'|| x == 'r' || x == 'd R' || x == 'T A')
Above is a snippet of java/ I have. What it does is takes an input -- then checks for a match. The bug I'm looking to resolve is if there are spaces after or before it isn't recognized.
以上是我拥有的 java/ 片段。它所做的是接受一个输入——然后检查匹配。我要解决的错误是如果在无法识别前后有空格。
For example within the input someone can type 'D R' no problem. If a space is added like so 'D R ' then it no longer recognizes the input.
例如,在输入中,有人可以输入“DR”没问题。如果像这样添加空格 'DR ' 那么它就不再识别输入。
Is there something I can do to affect the input to ensure no space before/after prior to button click? I've been looking into replace, but can't seem to get it going.
我可以做些什么来影响输入以确保在单击按钮之前/之后没有空格?我一直在寻找更换,但似乎无法让它继续。
A reference for what I've been looking at : http://www.w3schools.com/jsref/jsref_replace.asp
我一直在看的参考资料:http: //www.w3schools.com/jsref/jsref_replace.asp
回答by ?????
回答by Gopinath Koothaperumal
回答by Gaurang Tandon
You can do a check before-hand:
您可以事先进行检查:
if (!String.prototype.trim) {
String.prototype.trim = function () {
return this.toString().replace(/^\s+|\s+$/g, '');
};
}
Will enable .trim
in non-supported browsers. And then, you can use it like:
将.trim
在不受支持的浏览器中启用。然后,您可以像这样使用它:
var x = $("#clueOneInput").find('input[type=text]').val().trim();
With the benefit that you can use this .trim
method at many other places in the code too.
好处是您也可以.trim
在代码的许多其他地方使用此方法。
回答by Amit Joki
Do this for cross-browser:
为跨浏览器执行此操作:
var x = $("#clueOneInput").find('input[type=text]').val().replace(/^\s+|\s+$/g,"");
回答by Naveen Chandra Tiwari
You should always use $.trim() while comparing the string. You can use $.trim() like:
在比较字符串时,您应该始终使用 $.trim()。您可以使用 $.trim() 像:
if($.trim(x) == 'D R' || $.trim(x) == 'd r'|| $.trim(x) == 'D r'|| $.trim(x) == 'd R'|| $.trim(x) == 'd'|| $.trim(x) == 'r' || $.trim(x) == 'd R' || $.trim(x) == 'T A')