Reputation: 778
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
.
Upvotes: 0
Views: 224
Reputation: 1
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" />
Upvotes: 2
Reputation: 93203
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);
})
Upvotes: 1