pop pop - 1 month ago 8
Javascript Question

When I enter 2 letters it searches about one one I would search about 2 letters at once to get value

enter image description here[enter image description here][2]When I enter 2 letters it searches about one one I would search about 2 letters at once to get value

function d() {
var keyy = ["ا","ب","ت","ث","ج","ح","خ","د","ذ","ر","ز","س","ش","ص","ض","ط","ظ","ع","غ","ف","ق","ك","ل","م","ن","ه","و","ي"," ",","];
var code = ["ي1", "س1", "و1","ع1","ي2","س2","و2","ع2","ي3","س3","و3","ع3","ي4","س4","و4","ع4","ي5","س5","و5","ع5","ي6","س6","و6","ع6","ي7","س7","و7","ع7"," /",","];

var msg=document.getElementById("pop").value;//if value = 1س it Gives unfounded???

var finalcode="";

for (var i = 0, len = msg.length; i < len; i++)
{
var index=code.indexOf(msg[i]);

if(code[index]==undefined)
finalcode+=msg[i];
else
finalcode+=keyy[index];
}

document.getElementById("p").innerHTML = finalcode;
}

Answer Source

If I understand what's going on, your problem is this line:

var index = code.indexOf(msg[i]);

msg[i] is the same thing as msg.charAt(i), which only gives you a single character from the string. If you want to check two characters per index, you need to use String#substr(start, length) with a length argument of 2:

var index = code.indexOf(msg.substr(i, 2));

Secondly, you should change your for loop if you plan to check 2 characters at a time, to something like this:

for (var i = 0, len = msg.length; i < len; i += 2)

And lastly, while the line

if (code[index] == undefined)

does work, a more robust check would be to make sure the index itself is valid:

if (index < 0)

All together, you get this code:

function d() {
  var  keyy = ["ا","ب","ت","ث","ج","ح","خ","د","ذ","ر","ز","س","ش","ص","ض","ط","ظ","ع","غ","ف","ق","ك","ل","م","ن","ه","و","ي"," ",","];
  var code = ["ي1", "س1", "و1","ع1","ي2","س2","و2","ع2","ي3","س3","و3","ع3","ي4","س4","و4","ع4","ي5","س5","و5","ع5","ي6","س6","و6","ع6","ي7","س7","و7","ع7"," /",","];

  var msg = document.getElementById("pop").value;
  var finalcode = "";

  for (var i = 0, len = msg.length; i < len; i += 2)
  {
    var index = code.indexOf(msg.substr(i, 2));

    if (index < 0)
      finalcode += msg.substr(i, 2);
    else
      finalcode += keyy[index];
  }

  document.getElementById("p").innerHTML = finalcode;
}