删除 Javascript 变量中的空格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13613680/
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 spaces in a Javascript variable
提问by Naveen Gamage
I'm using AJAX to retrieve data from MYSQL database through PHP.
我正在使用 AJAX 通过 PHP 从 MYSQL 数据库中检索数据。
However, if there is no result found, the variable still has two spaces. I found the problem using alert(data.length);
. The result is 2, which means there are two spaces.
但是,如果没有找到结果,变量仍然有两个空格。我发现问题使用alert(data.length);
. 结果是2,这意味着有两个空格。
How can I remove these spaces so that if there is no result, I could display a message using if(data == ''){}
?
如何删除这些空格,以便如果没有结果,我可以使用if(data == ''){}
?
Thank you!
谢谢!
回答by VisioN
回答by Bruno
I can't understand why you have those two empty spaces in the first place. If it's a suitable option for you, I would try to remove those spaces at the origin, so from the server response.
我不明白为什么你首先有这两个空位。如果它对您来说是一个合适的选择,我会尝试从服务器响应中删除源处的那些空格。
If that's not possible you could use String.prototype.trim
to remove leading/trailing white space. This would allow you to write your check as below
如果这是不可能的,您可以使用String.prototype.trim
删除前导/尾随空格。这将允许你写你的支票如下
if (data.trim().length === 0) {
...
}
回答by lostsource
var str = "lots of whitespace";
str.replace(/\s+/g, ''); // 'lotsofwhitespace'
回答by David Müller
See this post where the topic is covered deeply, if you use jQuery, you can use $.trim()
which is built-in.
回答by echo_Me
if your variable is data
then try this
如果你的变量是data
然后试试这个
data.replace(/\s+/g, '');
and assign it to other variable if you want
并根据需要将其分配给其他变量
data2 = data.replace(/\s+/g, '');
回答by KingKongFrog
3 options:
3个选项:
var strg = "there is space";
strg.replace(/\s+/g, ' ');
or:
或者:
$.trim()
or:
或者:
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, "");
}
var strg = "there is space";
strg.trim();
回答by AJ Genung
data = data.split(' ').join('')
that will remove all spaces from a string.
data = data.split(' ').join('')
这将从字符串中删除所有空格。