0

I have this code that removes any Numeric values from an input field.

This works fine but the issue is that it will also remove the Spaces too which is not wanted.

This is my code:

$(document).on('keyup','.myclassname', function(e){
  var regexp = /[^a-zA-Z]/g;
  if($(this).val().match(regexp)){
    $(this).val( $(this).val().replace(regexp,'') );
  }
});

Can someone please advice on this?

7
  • 2
    Try this regex /[0-9]+/g Commented Aug 17, 2017 at 16:34
  • /[^a-zA-Z]/g is any character that's no in the alphabet, including whitespace and punctuation (and numbers, which you want). Commented Aug 17, 2017 at 16:35
  • See this stackoverflow.com/questions/45730059/… for the same issue. Commented Aug 17, 2017 at 16:36
  • You can examine what keycode user attempted to enter and forbid entry if it is numeric instead of replacing it after entry. Commented Aug 17, 2017 at 16:37
  • 1
    Possible duplicate of Removing Numbers from a String using Javascript Commented Aug 17, 2017 at 16:39

2 Answers 2

3

your regex currently matches everything that is not english alphabet, if you only want to remove numeric content you can /[0-9]/g or /\d/g

  var str = "1A3 AAA";
  var regexp = /[0-9]/g;
  console.log(str.replace(regexp, ""));

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

2 Comments

You can improve this by using \d. Which is shorthand for [0-9]
str.replace(/\d/g, '') would work too, to use the \d wildcard
2

A quick answer would be to change this

var regexp = /[^a-zA-Z]g;

To this

[^a-zA-Z\s]

This means: Match a single character not present in the list below, characters from a-z, A-Z and \s (any whitespace character)

A shorter version, would be:

[0-9]+

This means: Match a single character PRESENT in the list below, Matching between one and unlimited times, only numbers from 0 to 9, achieving what you are really trying to do "remove any numeric values"

An even shorter version, would be:

[\d]+

Wich is equal to [0-9]+

Previously, you are excluding the characters you don't want, but is easier, shorter and faster if you select only the ones you want.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.