0

i'm having the following code:

var specialchars = [246,214,228,196,252,220,223]; // holds german umlauts + ß
var foo = "abcdefä41hl";

what's the best practise for detecting if foo contains a character's ascii-code from the array? in that case it would return true as it contains "ä" (ascii code 228).

thanks

1
  • JavaScript uses the UTF-16 encoding of Unicode, not ASCII. So ß, for example, is better written as "ß" or "\u00df". (ß isn't even an ASCII character.) So, why not make specialchars an array of strings? Commented Nov 11, 2016 at 3:24

2 Answers 2

1

You can detect that by,

var specialchars = [246,214,228,196,252,220,223];
var foo = "abcdefä41hl";
var isExist = !!([...foo].find(itm => specialchars.includes(itm.charCodeAt())));

console.log(isExist); // true

Or you could use Array.prototype.some instead of find as suggested in the comment,

var isExist = [...foo].some(itm => specialchars.includes(itm.charCodeAt()));
Sign up to request clarification or add additional context in comments.

5 Comments

You might want Array#some instead of find, so that it returns a boolean.
@4castle Updated! Thanks for the heads up.
sorry to bother you but is [...foo] the correct syntax? it's not working .. :/ would you please update the solution?
@Fuxi Nothing is gonna bother me. :-) Are you using ES6? That one is called as spread operator.
@Fuxi If [...foo] isn't working, you can also do foo.split('') for that part.
0

Quite easily:

foo.split("").filter(c => specialchars.indexOf(c.charCodeAt()) != -1).length != 0

It splits the string to an array of chars, keeps only the ones that exist in the list of special characters and checks if any are left.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.