删除 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 19:17:08  来源:igfitidea点击:

Remove spaces in a Javascript variable

javascript

提问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

This is called string trimming. And here is one option for that in pure JavaScript:

这称为字符串修剪。这是纯 JavaScript 中的一种选择:

var len = data.replace(/\s/g, "").length;

However, in modern browsers there is a string trim()function for that:

但是,在现代浏览器中,有一个字符串trim()函数:

var len = data.trim().length;

回答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.trimto 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.

请参阅这篇文章,其中深入介绍了该主题,如果您使用 jQuery,则可以使用$.trim()which 是内置的。

回答by echo_Me

if your variable is datathen 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('')这将从字符串中删除所有空格。