Naveen Gamage
Naveen Gamage

Reputation: 1884

Remove spaces in a Javascript variable

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

Answers (7)

AJ Genung
AJ Genung

Reputation: 341

data = data.split(' ').join('') that will remove all spaces from a string.

Upvotes: 1

Bruno
Bruno

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

KingKongFrog
KingKongFrog

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

echo_Me
echo_Me

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

David Müller
David Müller

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

lostsource
lostsource

Reputation: 21850

var str = "lots of whitespace";
str.replace(/\s+/g, ''); // 'lotsofwhitespace'

Upvotes: 1

VisioN
VisioN

Reputation: 145458

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

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

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

var len = data.trim().length;

Upvotes: 9

Related Questions