3

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!

3

7 Answers 7

9

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;
Sign up to request clarification or add additional context in comments.

1 Comment

but I don't want to remove spaces if there are some results, then spaces in those results will be also removed..I can try, if data.length == 2 then i can trim it.. thank you for ur answer...
3

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) {
  ...
}

Comments

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

Comments

1

See this post where the topic is covered deeply, if you use jQuery, you can use $.trim() which is built-in.

Comments

1

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, '');

Comments

1

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();

1 Comment

but I don't want to remove spaces if there are any results, then spaces in those results will be also removed.. now I can do if data.length == 2 then trim it using ur way.. thank you very much..
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.