Proper Use of IndexOf in JavaScript

I have a simple JavaScript statement that reads a string and launches a URL based on what it contains, but I'm not sure if I used it correctly IndexOf, so I just wanted to check.

Here is my code snippet:

<script type="text/javascript"> 

var mc_u1 = "somevariable";

if (mc_u1.indexOf("1|Accept") > 0) {
document.writeln("<img src=\"https://www.someurl1.com\">");
}

if (mc_u1.indexOf("1|Refer") > 0) {
document.writeln("<img src=\"https://www.someurl2.com\">");

}

if (mc_u1.indexOf("2|Accept") > 0) {
document.writeln("<img src=\"https://www.someurl3.com\">");

}

if (mc_u1.indexOf("2|Refer") > 0) {
document.writeln("<img src=\"www.someurl4.com\">");

}

</script>

As you can see from the above code, what I'm trying to do is based on the contents of the variable to mc_u1disable the URL (which are different, although I just masked them for obvious reasons).

My question is: if the variable mc_u1starts with say 1|Accept, should I use > -1a Javascript Statement or > 0?

Hope this makes sense!

+3
source share
4 answers

MDN:

string.indexOf(searchValue[, fromIndex])

String , fromIndex, -1, .

, , "1|Accept", , indexOf 0.

+4

0 - , , , > 0 . > -1 == 0 .

+3

== 0, 0

0

All Articles