1

I am trying to make ifcondition for a large number of chars.

I can use

if (str==!||str==@||str==#||str==$||str==^||str==&)

And so on, but this seems very inefficient. I would like to get the condition to work if the char is on of those:

!@#%$^&()_-+=\?/.,'][{}<>`~

Is there is any shorter and more efficient way of doing it?

for (var c0 = 1; c0 > fn.length++; c0++) {
 var str = fn.charAt(c0--);

 if (str ==-"!@#%$^&()_-+=\?/.,'][{}<>`~") {

 }
}

I want the check to accrue on every single char from the string above.

Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
Aviv Aviv
  • 129
  • 1
  • 10
  • 1
    What you want is a Regular Expression. See [this](https://stackoverflow.com/questions/4736/learning-regular-expressions). – holydragon Jan 25 '19 at 07:40

3 Answers3

2

You can use a regular expression character class to check if your character matches a particular character:

/^[\!@#%$\^&\(\)_\-\+=\?\/\.,'\]\[\{\}\<\>`~]$/

Here I have escape special characters so that they get treated like regular characters.

See working example below:

const regex = /^[\!@#%$\^&\(\)_\-\+=\?\/\.,'\]\[\{\}\<\>`~]$/,
charA = '@', // appears in char set
charB = 'A'; // doesn't appear in char set

console.log(regex.test(charA)); // true
console.log(regex.test(charB)); // false

Alternatively, if you don't want to use regular expressions you can instead put all your characters into an array and use .includes to check if your character is in your array.

const chars = "!@#%$^&()_-+=\?/.,'][{}<>`~",
charArr = [...chars],
charA = '@', // is in char set
charB = 'A'; // isn't in char set

console.log(charArr.includes(charA)); // true
console.log(charArr.includes(charB)); // false
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
1

Just use regular expressions rather than manual single character checking.

const pattern = new RegExp("!@#%$^&()_-+=\?\/.,'][{}<>`~");
const exists = pattern.test(str);

if (exists) { 
  // code logic for special character exists in string
}
Danyal Imran
  • 2,515
  • 13
  • 21
  • @Andreas thanks update, that occurs when you are using / character inside the regex, since its a special character to regex it must be escaped by the \ character – Danyal Imran Jan 25 '19 at 07:48
  • You have to escape _all_ special characters when using `new RegExp(...)` – Andreas Jan 25 '19 at 08:31
0

First you can use split('') to split a string into an array of characters. Next you can use .some to check if a condition is true for at least one element in the array:

"!@#%$^&()_-+=\?/.,'][{}<>`~".split('').some(x => x === str)
Lux
  • 17,835
  • 5
  • 43
  • 73