Regex to prevent the same character from appearing more than 3 times in a row

Viewed 605

I want a javascript function that will prevent the same character from appearing more than 3 times in a row in an input field. I know how to do this easily with 1 repeat. For example...

function deleteit() {message.value=message.value.replace(/(.)\1/g,'')} 
<input type='text' id='message' onkeyup='deleteit()'>

If you enter the same character more than once here, the second gets deleted. I want to allow up to 3 and delete on the 4th. For example, "Yippy!!!" would be acceptable but typing "Yippy!!!!" would delete the 4th exclamation point. I tried changing the regex to /(..)\1/g That does work, but not quite. It's deleting 2 "Groups" of characters, so if I typed something like "YOYO" it would delete that. How can I change 4 or more of the same character to 3.

2 Answers

You can use

function deleteit() {message.value=message.value.replace(/(.)(\1{2})\1+/g,'$1$2')}
<input type='text' id='message' onkeyup='deleteit()'>

See the regex demo. Details:

  • (.) - Capturing group 1 ($1): any char but a line break char
  • (\1{2}) - Capturing group 2 ($2): two chars that are equal to the one captured in Group 1
  • \1+ - one or more occurrences of the same char as the one captured in Group 1.

Or, alternatively:

function deleteit() {message.value=message.value.replace(/((.)\2{2})\2+/g,'$1')}
<input type='text' id='message' onkeyup='deleteit()'>

Regex details

  • ((.)\2{2}) - Group 1 ($1 in the replacement pattern refers to this group value):
    • (.) - Group 2: any char but a line break char
    • \2{2} - two occurrences of the Group 2 value
  • \2+ - one or more occurrences of Group 2 value

See the regex demo.

Related