1

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.

3 Answers 3

2

Just invert your regex by adding ^ inside []

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

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

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

Comments

0

Try this

var val = "123gdf$£!".replace(new RegExp("[0-9a-zA-Z]", "g"), "");

https://jsfiddle.net/wx38rz5L/1816/

Comments

0

Simply you can use string match() method of javascript.

Here it is:

var val= "123gdf$£!";
var result= str.match(/^[a-zA-Z0-9- ]*$/);

result will be an array with values.

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.