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?

Dij
  • 9,761
  • 4
  • 18
  • 35
David Hope
  • 1,426
  • 4
  • 21
  • 50

2 Answers2

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, ""));
Dij
  • 9,761
  • 4
  • 18
  • 35
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.

Rudy Palacios
  • 122
  • 2
  • 8