Reputation: 1884
I'm using AJAX to retrieve data from MYSQL database through PHP.
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.
How can I remove these spaces so that if there is no result, I could display a message using if(data == ''){}
?
Thank you!
Upvotes: 3
Views: 21101
Reputation: 341
data = data.split(' ').join('')
that will remove all spaces from a string.
Upvotes: 1
Reputation: 6000
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
if (data.trim().length === 0) {
...
}
Upvotes: 3
Reputation: 14419
3 options:
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();
Upvotes: 1
Reputation: 37253
if your variable is data
then try this
data.replace(/\s+/g, '');
and assign it to other variable if you want
data2 = data.replace(/\s+/g, '');
Upvotes: 1
Reputation: 5351
See this post where the topic is covered deeply, if you use jQuery, you can use $.trim()
which is built-in.
Upvotes: 1
Reputation: 21850
var str = "lots of whitespace";
str.replace(/\s+/g, ''); // 'lotsofwhitespace'
Upvotes: 1