1

I have a text box on a HTML page, the idea is that the user can enter any text into the box and then Jquery will remove every other than letters of the alphabet.

This is what I have come up with, it works for small text samples, 1-2 lines, however anything over this it only works on a small section of the input text, is there a better way to do this?

$("#read").change(function () {
    read = $("#read").val().toLowerCase().replace(/[^a-z]+/, '');
    $("#read").val(read);
});
1
  • 1
    replace() is not a jquery method. Commented Jan 31, 2012 at 22:50

2 Answers 2

3

add /gi to end of your regular expression

/[^a-z]+/gi

then it will replace all occurrences through whole string.

g (for global) and i (for ignore case)

with the comments of @Lunar this is how your code should look like

$("#read").change(function () {
     $(this).val($(this).val().replace(/[^a-z]/gi, ''));
   });
Sign up to request clarification or add additional context in comments.

2 Comments

@Lunar Notice that the i flag ignores case, so you don't need toLowerCase() unless you want your output to be in lowercase.
@Lunar Also, just use this.value = this.value.replace(/[^a-z]/gi, ''). There really is no need for all that jQuery in the function body. Also note that the + is unnecessary since you have set g anyway (though it also doesn't hurt to have it).
1

You need to enable the regex's global flag, so that it will replace all matches instead of just the first match.

/[^a-z]+/ig

More about JS regular expressions.

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.