Escape Single and double quotes from the same text area giving crlt + V

4

// I want to just not let you enter single quotes and double quotes

$('#bot').keypress(function (e) {
    var regex = new RegExp("^[a-zA-Z0-9-]+$");
    var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
    if (regex.test(str)) {
        return true;
    }

    e.preventDefault();
    return false;
});
    
asked by anonymous 09.05.2018 / 18:50

3 answers

1

You can use the following Regex :

$('#bot').on('keypress', function (e) {

    if (!/['"]/.test(String.fromCharCode(e.keyCode))) {
        return;
    } else {
        e.preventDefault();
    }
}); 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Digite algo: <textarea id='bot'></textarea>
    
09.05.2018 / 19:05
13

The problem with keypress is that it will not recognize if the data comes from other sources, ie it will not work with Ctrl + V or with the right click of the mouse.

I first recommend using .on('input') and instead of having to check character by character:

String.fromCharCode(!e.charCode ? e.which : e.charCode)

You can simply use .replace in .val() or .value

So:

$('#bot').on('input', function (e) {
   this.value = this.value.replace(/['"]/g, "");
}); 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Digite algo: <textarea id='bot'></textarea>

This will work when you type and when you use Ctrl + V, you will not need to add all events, such as:

  • .on('keypress')
  • .on('paste')
09.05.2018 / 21:22
0

You can do this by just checking the single quotes and quotation marks with a simple if:

$(function(){
  $('#bot').keypress(function (e) {      
      var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
      if (str == '"' || str == "'") {
          return false;
      }
      return true; 
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><textareaid="bot"></textarea>

I do not know what your concern is about the quotes, but you can also replace them with HTML Entities , as follows:

$(function(){
  $('#bot').keypress(function (e) {      
      var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
      if (str == '"') {
      		$(this).html($(this).val() + '&quot;');
          return false;
      }
      if (str == "'") {
      		$(this).html($(this).val() + '&apos;');
          return false;
      }
      return true; 
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><textareaid="bot"></textarea>

So the user can use the quotation marks and you will have HTML Entities instead of the quotation marks behind.

    
09.05.2018 / 18:56