Oded Harth
Oded Harth

Reputation: 4406

comparing strings in javascript

I am comparing two strings that supposed to be equal. From some reason it thinks they are not.

this is the code:

   function(){
    prev = $('h').value;
    now = $('content').innerHTML;
    alert(prev);
    alert(now);
    if(prev == now)
    {
    $('content').fade({ duration: 3.0, from: 0, to: 1 });
    }
    else{alert('lol');}
    }

I made added the alert functions to be sure they are equal.

Any idea why it gives me the "alert('lol)" ?

Upvotes: 2

Views: 460

Answers (3)

Spudley
Spudley

Reputation: 168685

Two strings may look the same in an alert box but not be the same. For example, spaces at the beginning or end of one of the strings.

I find if I have this problem, I can spot it more easily by adding markers to the string when I alert it, like so:

alert('['+mystring+']');

Also, console.log() is a more powerful way to debug this sort of thing than alert(). console.log() is available in most modern browsers when using their built-in developer tools (in Firefox, you need to install the Firebug plugin for this).

If you find you have leading/trailing spaces to get rid of, you can do so very easily with a quick regex:

mystring = mystring.replace(/((^\s)|(\s$))/,'');

This will remove all white-space from the beginning and end of the string.

Hope that helps.

Upvotes: 1

Sarfraz
Sarfraz

Reputation: 382686

Your code is incorrect:

You need to use val() instead of value with jQuery selector or convert it to DOM element with get or [0] shorthand to use value.

value gives you what is inside value attribute while innerHTML gives you the inner html of an element. You should either use value for both elements or innerHTML depending on the type of elements :)

Example:

prev = $('h').val();
now = $('content').val();

if(prev == now)

Or:

prev = $('h')[0].innerHTML;
now = $('content')[0].innerHTML;

if(prev == now)

Upvotes: 1

Frédéric Hamidi
Frédéric Hamidi

Reputation: 262919

Your strings are probably different, but it's hard to see leading and trailing whitespace in alert() boxes. You can try to trim() the strings:

if ($.trim(prev) == $.trim(now)) {
    $('content').fade({ duration: 3.0, from: 0, to: 1 });
}

Upvotes: 1

Related Questions