0

I'm comparing two strings. For some reason no matter how I try to compare them, it appears as if they're not equal but they are.

logger.trace("eval Str: "+util.inspect(evalStr));
logger.trace("Is next():" + evalStr == "next()");
logger.trace("Is next():" + evalStr.valueOf() == "next()".valueOf());
logger.trace(toHex(evalStr));
logger.trace(toHex("next()"));

2016-10-02T12:10:55.446-04:00 - trace: eval Str: 'next()'
2016-10-02T12:10:55.447-04:00 - trace: false
2016-10-02T12:10:55.448-04:00 - trace: false
2016-10-02T12:10:55.448-04:00 - trace: 6e6578742829
2016-10-02T12:10:55.449-04:00 - trace: 6e6578742829


function toHex(str) {
    var hex = '';
    for(var i=0;i<str.length;i++) {
        hex += ''+str.charCodeAt(i).toString(16);
    }
    return hex;
}

1 Answer 1

3

The problem is the + in the trace calls, you're not comparing what you think you're comparing. You want to add explicit () so you're grouping the way you want to group:

logger.trace("Is next():" + (evalStr == "next()"));
// Note --------------------^-------------------^

Why:

Your original code:

logger.trace("Is next():" + evalStr == "next()");

...is evaluated like this:

logger.trace(("Is next():" + evalStr) == "next()");
// Note -----^----------------------^

...which is why you're not seeing Is next(): in the output. "Is next():next()" == "next()" is false, so... :-)


And == or === are the correct way to compare strings in JavaScript. If both operands are strings, it doesn't matter which you use. If either of the operands may or may not be a string, use == if you want the abstract equality conversion rules (which are complicated) or === if you want the comparison to be false when the operands aren't the same type.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.