简体   繁体   中英

JavaScript - Replace some letters with numbers

I'm trying replace some letters with numbers in JQuery, and I have initialized my object like this:

var myVar = {'a':1, 'b':2, 'c':3, 'd':4}

I'm getting the string from an input and I want to convert these letters immediately as the user is typing in text input. I want to do it via RegEx .

You can use input event, String.prototype.replace() , RegExp() with parameter new RegExp(keys.join("|"), "g" where keys are property names of myVar object

 var myVar = {"a":1, "b":2, "c":3, "d":4}; var keys = Object.keys(myVar); document.querySelector("input") .addEventListener("input", function(e) { e.target.value = e.target.value.replace(new RegExp(keys.join("|"), "g") , function(match) { return myVar[match] }); }); 
 <input type="text" /> 

Use :

  • Event : keyup event

  • Action : split & join for String AND map for Array .

     $(INPUT_SELECTOR).keyup(function(event){ var newVal=$(this).val().split('').map(function(ch){ if(isFinite(ch) || !myVar[ch]){ return ch; }else{ return myVar[ch]; } }).join(''); $(this).val(newVal); }) 

DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM