0

I have a input string when user enter data into the string then find out the string contains some specified (!@#$%) special characters are found or not. The following string values output like

 string str="Mn@"; --> true string str="m@*"; --> false string str="@Mn"; --> true string str="Mn&"; --> false string str="@"; --> true string str="M"; --> false string str="*"; --> false string str=" "; --> false string str=" Mn"; --> false string str="M *"; --> false string str="m@ "; --> false 

3 Answers 3

2

Use a regular expression, and put all the characters you want to search for into a character set:

const pattern = /[!@#$%]/; console.log(pattern.test('Mn@')); console.log(pattern.test('@Mn')); console.log(pattern.test('Mn&')); console.log(pattern.test('@')); console.log(pattern.test('M')); console.log(pattern.test('*'));

For your new question, add negative lookahead for a space if you want to ensure the text doesn't contain a space:

const pattern = /^(?!.* )[!@#$%]/; console.log(pattern.test('Mn@')); console.log(pattern.test('@Mn')); console.log(pattern.test('Mn&')); console.log(pattern.test('@')); console.log(pattern.test('M')); console.log(pattern.test('*')); console.log(pattern.test(' ')); console.log(pattern.test(' Mn')); console.log(pattern.test('M *')); console.log(pattern.test('m@ *'));

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

2 Comments

/[!@#$%]/ this pattern not consider spaces. I want to check all special characters except !@#$% these.
Best to state your problem upfront in the question, before answers start coming in - if you want to exclude text with spaces, negative lookahead for a space in the pattern.
0

You can create a reusable function that will check that validation for you:

var spChar = '!@#$%'; function isIncludeSpecialChar(stringVal){ return spChar.split('').some((character) => stringVal.includes(character)); } console.log(isIncludeSpecialChar('Mn@')); console.log(isIncludeSpecialChar('@Mn')); console.log(isIncludeSpecialChar('Mn&')); console.log(isIncludeSpecialChar('@')); console.log(isIncludeSpecialChar('M')); console.log(isIncludeSpecialChar('*'));

Comments

0

You can use test and match functions in JS regex. test will give you if a character is present or not and match will give which character is present in the string

var str1="Mn@"; console.log(/[!@#$%]/.test(str1)) console.log(str1.match(/[!@#$%]/))

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.