0

having a problem using regular expression to allow only certain characters. The problem is when i try to insert a character into words to correct errors. When i try to insert the new char the cursor move to the end of the input box.

this is the code i use:

$('body').on('input','.info',function() {
        this.value = this.value.replace(/[^a-zA-Z0-9+&,*_\- \b \r ]/g, '');

Any hints?

Thank you in advance

1 Answer 1

2

You need to save the character index (the selectionStart) so you can reposition to it after value change is complete, if a value change needs to be made:

$('body').on('input', '.info', function(e) {
  const index = this.selectionStart - 1;
  const replaced = this.value.replace(/[^a-zA-Z0-9+&,*_\- \b \r ]/g, '');
  if (replaced !== this.value) {
    this.value = replaced;
    this.selectionStart = index;
    this.selectionEnd = index;
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="info">

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.