简体   繁体   中英

Using a colon as a separator in javascript

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.

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 .

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

Your test should read:

if (data.indexOf(":") >= 0) {
    ...
}
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.");
}

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM