How to strip HTML ASCII codes from a string using Javascript
I have a string that I'm building dyn开发者_运维百科amically while a user is entering data into a textbox, I'm capturing input as it's being entered and saving it to a global variable as follows:
e.g.
var uid = '';
function buildString(e) {
var keynum = e.keyCode ? e.keyCode : e.which;
uid += String.fromCharCode(keynum);
}
I notice that the string has HTML ASCII codes appended in front of each character that was typed.
e.g.
091[041)062>030RS04800546029GS
so
091 = [
041 = )
062 = >
048 = 0
etc.
I don't want these codes to be present in the string, is there a regex, or some other method in Javascript, that will strip just the codes out without stripping actual, valid, numbers that were entered?
It sounds like you're not using the best event for what you're trying to do. Your code should mostly work for the keypress
event (example), but won't work well at all for keyup
or keydown
.
But just listening for keypress
won't let you build up a string of what keys were pressed. For instance, using the example above, if I type "abcd" then right-arrow twice then "xx", the built-up string will be "abcdxx" where what's showing in the text box is "abxxcd". So more sophistication will be required.
Here there be dragons. For a good idea of the madness around JavaScript keyboard events, this site has great information.
精彩评论