1

How can I determine if any individual character in src matches any individual character in restricted? I have this JS method which does the job, but I'd like to improve it if I can:

function CheckRestricted(src, restricted) { for (var i = 0; i < src.length; i++) { for (var j = 0; j < restricted.length; j++) { if (src.charAt(i) == restricted.charAt(j)) return false; } } return true; } 

If this were C#, I could achieve this with LINQ in a single line:

bool CheckRestricted(string src, string restricted) { return src.Any(s => restricted.Contains(s)); } 

Is there some sort of similar functionality in JS that I'm unaware of?

EDIT: Sample use case:

CheckRestricted("ABCD", "!+-=;:'`"); //true CheckRestricted("ABCD!", "!+-=;:'`"); //false 

It is predominantly used to disallow 'special characters'.

3

1 Answer 1

5
function CheckRestricted(src, restricted) { return !src.split("").some(ch => restricted.indexOf(ch) !== -1); } 
Sign up to request clarification or add additional context in comments.

7 Comments

The second .split("") is not necessary
You can use String.prototype.includes()
This seems to work for me, at least it does using a web-based JS compiler. For some reason Visual Studio 2013 gives a syntax error on =>? But what does VS know about JS, anyways :)
@Andreas thx, looks nicer that way and more efficient. And yeah missunderstood when it should return true, changed
@sab669 => sintax is ecmascript 6, you could always do the old function (ch) {return estricted.indexOf(ch) !== -1}
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.