Shaiwal Tripathi
Shaiwal Tripathi

Reputation: 627

indexOf is not getting the exact Value in javascript

I am checking that a particular value of an array is exist in a string or not. For that I had implemented the following code

function Check() {
        var Value = 'I III';
        var Opt = new Array("I", "II", "III", "IV");
        for (var i = 0; i < Opt.length; i++) {
            if (Value.indexOf(Opt[i]) > -1) {
                alert("Hello");
            }
        }
    }

if value exists in string it should display an alert, but the problem is that it display the alert 3 times instead of 2 times, because indexOf is assuming II as a part of string because III exists in string.

Upvotes: 2

Views: 580

Answers (2)

sailaja.p
sailaja.p

Reputation: 216

This is the another way to get the ans

function Check() {

    var Value = 'I III'.split(" "); var Opt = ["I", "II", "III", "IV"];

    for (var i = 0; i < Opt.length; i++) {

        if (Value.indexOf(Opt[i]) > -1) {

            alert("Hello");

        }
    }
}Check();

Upvotes: 0

royhowie
royhowie

Reputation: 11171

The easiest way to work around this would be to split Value with a delimiter (e.g., at each space) with String.prototype.split:

var value = 'I III'.split(' ')
var options = ['I', 'II', 'III', 'IV']

options.forEach(function(option) {
  var index = value.indexOf(option)
  if (index !== -1) {
    // don't use `document.write` in general; it's just very useful in stack snippets
    document.write(index + ' : ' + value[index])
    document.write('<br>')
  }
})

A couple notes:

  • don't capitalize your variable names; use camelCase for variables and PascalCase for classes/etc
  • don't use new Array(); instead prefer the array literal: []

Upvotes: 6

Related Questions