jmosawy jmosawy - 4 months ago 34
jQuery Question

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
.

Answer

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" />