user1999453 user1999453 - 2 months ago 5x
jQuery Question

How to get all value of invalid characters in a string in jquery?

I have a jquery method that check special character as shown below:

function checkForSpecialChar(val) {

if (val != 0 && /^[a-zA-Z0-9- ]*$/.test(val) == false) {

return false;

return true;

This is working fine as it validate the value correctly.

However now I need to get all invalid characters for the val string and show it to the user.

So for example
if val is = 123gdf$£!

It should get only the invalid character which is

Any idea how i can do that please?

Thanks in advance for any help.


Just invert your regex by adding ^ inside []

[^a-zA-Z0-9- ] // match anything that is not alphanumerical, `-` or whitespace 

  'Invalid characters of "123gdf$£!": '
  + (
    '123gdf$£!'.match(/[^a-zA-Z0-9- ]/g)