I have this script JsFiddle and I am trying to change submitted characters, but when you press for ex: s twice as in ss instead of showing xx it changes it to ss
Full code:
<body>
<div id='out'></div>
<textarea id="in" name="messages" onkeyup="test()"></textarea>
<input type="submit" id="submit" name="submit" />
Js function:
function test(){
var origin = document.getElementById("in").value;
var send = document.getElementById("out");
if(origin =='s'){
origin = 'z';
}
send.innerHTML = origin;
}
</script>
-
1Like this FIDDLEadeneo– adeneo2013年05月12日 18:53:35 +00:00Commented May 12, 2013 at 18:53
-
It seems like your example doesn't correctly match your real goal. Can you adjust your question to explain what you are really trying to do? In JS, there are many ways to check strings and modify input or output fields.Nicole– Nicole2013年05月12日 18:59:37 +00:00Commented May 12, 2013 at 18:59
-
@NickC Thank you, Just think of it this way, for every letter entered in English character, I need to replace them, to another Language, be it Arabic, Chinese, Russia... Now, that is why, I need to detect what key is pressed, and to change that key, with what I have in mind. But, that key needs to be there, after being changed.user1236473– user12364732013年05月12日 19:02:37 +00:00Commented May 12, 2013 at 19:02
2 Answers 2
var replacements = {
"s": "z",
// repeat for all the characters you want to replace
};
var neworigin = '';
for (var i = 0; i < origin.length; i++) {
neworigin += (origin[i] in replacements) ? replacements[origin[i]] : origin[i];
}
}
send.innerHTML = neworigin;
2 Comments
It looks like you want to replace all s characters with z before assigning to send. Your current code only replaces s with z if origin is exactly one s. Try this instead:
send.innerTHML = origin.replace(/s/g, 'z');
That will replace every occurrence of s with z in origin and assign the result to send.innerHTML. (In case it isn't obvious, with this you can get rid of the if statement.)
If you want to replace all characters with the same substitute character, you can change the regex from /s/g to /./g. If you want to replace each character with something else that depends on the character, you can use a look-up function:
var mapper = function(match) {
return match === 's' ? 'z' : '?'; // or whatever mapping function you want
}
send.innerHTML = origin.replace(/./g, mapper);
3 Comments
/s/g to /./g. See my updated answer.