最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Using a colon as a separator in javascript - Stack Overflow

programmeradmin0浏览0评论
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.

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.

Share Improve this question asked May 1, 2011 at 23:23 KeverwKeverw 3,7867 gold badges33 silver badges55 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 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.

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.

发布评论

评论列表(0)

  1. 暂无评论