Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.3k views
in Technique[技术] by (71.8m points)

jquery - Javascript Catch Special Characters on Paste, specifically TAB

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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));
  });
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...