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'.

sab669
  • 3,984
  • 8
  • 38
  • 75

1 Answers1

5
function CheckRestricted(src, restricted) {
   return !src.split("").some(ch => restricted.indexOf(ch) !== -1);
}
juvian
  • 15,875
  • 2
  • 37
  • 38
  • 3
    The second `.split("")` is not necessary – Andreas Apr 11 '17 at 16:08
  • You can use `String.prototype.includes()` – MultiplyByZer0 Apr 11 '17 at 16:10
  • 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 :) – sab669 Apr 11 '17 at 16:16
  • @Andreas thx, looks nicer that way and more efficient. And yeah missunderstood when it should return true, changed – juvian Apr 11 '17 at 16:16
  • @sab669 => sintax is ecmascript 6, you could always do the old function (ch) {return estricted.indexOf(ch) !== -1} – juvian Apr 11 '17 at 16:18
  • @juvian See here: http://js.do/code/146954 . The third one should pass validation – sab669 Apr 11 '17 at 16:30
  • @sab669 that is not the same function I made. There you are checking if ch is a substring of restricted, which is false in all cases – juvian Apr 11 '17 at 16:36