Disallowing repeated characters and space after punctuation

Posted on

Problem

I’m trying to “sanitize” a textarea input by disallowing repeated characters like “!!!”, “???”, etc. add spaces after commas, and I would like to optimize the code because I’m not a pro at this.

jsFiddle

$("#post_input").keypress(function() {
        var obj = this;
        setTimeout(function() {
            var text = obj.value;
            var selStart = obj.selectionStart;
            var newText = text.replace(/,{2,}|.{4,}|!{4,}|¡{4,}|?{4,}|¿{4,}/, function(match, index) {
                if (index < selStart) {
                    selStart -= (match.length - 4);  // correct the selection location
                }
                return(match.substr(0,1));
            });
            if (newText != text) {
                obj.value = newText;
                obj.selectionStart = obj.selectionEnd = selStart;
            }
        }, 1);
    });

    $("#post_input").blur(function(){
      this.value = this.value.replace( /,s*/g, ', ' );
    });​

I would like to merge all in only one regex and function.

Basically, I want to:

  • Prevent repeated characters (all kind of characters) to 3. No “aaaaa” or “!!!!!”
  • Add space after commas (,) or any kind of punctuation (!) (?) (.)

Solution

Prevent repetead characters (all kind of characters) to 3.

If you mean replace 4 or more repeated characters with single character:

str.replace(/(.)1{3,}/g, '$1');

Add space after commas (,) or any kind of punctuation (!) (?) (.)

str.replace(/[,.!?:;](?=S)/g, '$& ');

Leave a Reply

Your email address will not be published. Required fields are marked *