Search code examples
javascriptpythoncode-conversion

How to convert Python [... for ... in ... if ...] to JavaScript


In my previous question, some kind man gave me a good answer of check username.

This code checks whether username has some forbidden words.

Python:

FORBIDDEN_USERNAME_LIST = ['admin', 'master', 'owner']

for item in forbidden.FORBIDDEN_USERNAME_LIST:
    match = [nm for nm in FORBIDDEN_USERNAME_LIST if nm in username]
    if match:
        return JsonResponse({'result': item + 'banned username'})

I converted this code to JavaScript but some code is too hard for me to convert.

JavaScript:

for (item in FORBIDDEN_USERNAME_LIST){
    match = [nm for nm in FORBIDDEN_USERNAME_LIST if nm in username]
    //Here match = [...] code is hard for me to convert 
    if (match){
        console.log('exist')
    }
}

How can I convert this code to JavaScript?


Solution

  • Using regex in ES5:

    var FORBIDDEN_USERNAME_LIST = ['admin', 'master', 'owner'],
        username = "master",
        match = false;
    
    match = FORBIDDEN_USERNAME_LIST.some(function(pattern) {
      return new RegExp(pattern).test(username)
    });
    
    if (match) {
      console.log(username, 'exists');
    }