Welcome to 16892 Developer Community-Open, Learning,Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am trying to only allow ASCII characters for my input fields. The test Fiddle seems to not know what to do with a TAB character:

https://jsfiddle.net/jp2code/5enmojb2/77/

Yes, 77 iterations, so far. Feel free to look at all I have tried.

$().ready(function() {
  $('input').bind('paste', function(e) {
    var text = $(this).val();
    var txt2 = text.replace(/[^x00-x19]/g, ' ');
    $(this).val(txt2);
  });
});

ASCII Chart from Wikipedia used to determine that I do not want ASCII characters 0x00 to 0x19, hence the regular expression used above.

This last version has no errors, but it copies what is in the input box above into the input box below, including the TAB that I want to be replaced with a blank space.

How do I replace any occcurance of ASCII characters 0x00 to 0x19 with a single space?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
2.8k views
Welcome To Ask or Share your Answers For Others

1 Answer

Rather than replacing specific characters, I would argue what you really want is to replace everything except valid characters:

const ensureAscii = (x) => x.replace(/[^x20-x7e]/g, ' ');

$().ready(function() {
  $('input').bind('paste', function(e) {
    $(this).val(ensureAscii($(this).val()));
  });
});

Example:

ensureAscii('abc
123')
"abc  123"

Update: Your fiddle has a different problem. The text variable is empty! You need to get the pasted text from the clipboard:

const ensureAscii = (x) => x.replace(/[^x20-x7e]/g, ' ');

$().ready(function() {
  $('input').bind('paste', function(e) {
    const text = event.clipboardData.getData('text');
    $(this).val(ensureAscii(text));
  });
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to 16892 Developer Community-Open, Learning and Share
...