1
var data = "needactivation:9";
if (data.indexOf(":") == true) {
    replyData = data.split(":");
    if (replyData[0] == "needactivation") {
        alert("User Id Is " + replyData[1]);
    }
}
else if (data == "success") {
    window.location.href = "/";
}
else {
    alert("Unknown error.");
}

Is my JavaScript. It should alert the User ID but it gives a unknown Error. Any idea whats wrong with this script?

Not sure if this part matters, but i'm using the latest jQuery on the page also.

5 Answers 5

5

indexOf returns an index (or -1 if not found), not a boolean. Change this:

if (data.indexOf(":") == true) {

To this:

if (data.indexOf(":") !== -1) {

Alternatively, you could split regardless and then check replyData.length.

Sign up to request clarification or add additional context in comments.

Comments

2

String.indexOf() returns a number >= 0 when the string is found, not a boolean true value

Your test should read:

if (data.indexOf(":") >= 0) {
    ...
}

Comments

1
var data = "needactivation:9";
if (data.indexOf(":") >= 0) {
    replyData = data.split(":");
    if (replyData[0] == "needactivation") {
        alert("User Id Is " + replyData[1]);
    }
}
else if (data == "success") {
    window.location.href = "/";
}
else {
    alert("Unknown error.");
}

Comments

0

Try if (data.indexOf(":") != -1) {

Comments

0

In addition to verifying that the above answers are correct, I just wanted to say that you may also want to employ some kind of try/catch logic once you've changed your true to -1 since a string like Anything: will have an indexOf(":") >= 0 but will split in such a way that your reference to replyData[1] will throw yet another error.

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.