Replace javascript characters

2

I need to replace some characters with others in an input on the fly and I thought that with javascript I can solve it.

The theme is the following:  I have an input that reads EAN13 codes and I have it ready so that when I insert the numbers I validate it.

The fact is that now there is a bar code reading gun and when you click on the input and scan a code instead of writing numbers write the symbols that are in those numbers for example in the 6 put an & in 5 a% and so on with everyone. Then I need to write the javascript symbols to change the number assigned to that key to validate it and that humans understand it.

Can this be done with javascript? What would the syntax be?

    
asked by Killpe 24.04.2017 в 21:35
source

3 answers

8

The best way could be done by avoiding String.replace and regular expressions would be creating a dictionary manual and according to the character, loads the corresponding letter to the key in the dictionary.

Example (also in jsbin ):

var dic = {
  '&': '6',
  '%': '5',
  '#': '10',
  '(': 'N',
};

var resultadoLector = "(%#";
var resultadoHumano = "";
for (var i = 0; i < resultadoLector.length; i++) {
  resultadoHumano += dic[resultadoLector[i]];
}

console.log(resultadoHumano); //N510
    
answered by 24.04.2017 / 21:55
source
2

I leave an example with replace () as an alternative to the previous answer

let input = document.getElementById('inputCode')

input.addEventListener('keyup',function(){
  let code = this.value
  //Remplazar los valores
  code = code.replace('&','5')
  code = code.replace('%','6')
  // Convertir caracteres
  this.value = code
})
<input id="inputCode" placeholder="Insert your code"/>
    
answered by 24.04.2017 в 21:59
2

From what I understand the bar code gun instead of placing the numeric digits that are on the alphanumeric keyboard from 0 to 9 it places the signs that are on those keys.

If I am correct, here is an example of a input that when you write the signs that are on the keys from 0 to 9, these are replaced by your numerical contract (that is, ignore the key Shift :

//        0   1   2   3   4   5   6   7   8   9
signo = ["=","!",'"',"·","$","%","&","/","(",")"];
$(document).ready(function (){
 $("input").on("keydown",function (){
  n=signo.indexOf(event.key)
  if(n!=-1) {
   s=this.selectionStart;
   e=this.selectionEnd;
   a=this.value;
   this.value=a.substr(0,s)+n+a.substr(e)
   this.selectionStart=s+1;
   this.selectionEnd=e+1;
   return false
  }
 });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Codigo:<input> (hace caso omiso a la tecla shift)

On the other hand I suggest you review the manual of said pistol because surely such functionality must be able to be configured, I hope this helps you, Greetings! ;)) ..

    
answered by 24.04.2017 в 23:05