-8

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?

freginold
  • 3,946
  • 3
  • 13
  • 28
touchingtwist
  • 1,930
  • 4
  • 23
  • 38

4 Answers4

2
 const forbidden = ['admin', 'master', 'owner'];
 const username ="imanadmin;)";
 const found = forbidden.find(word => username.includes(word));
 if(found) return res.json({'result': found + ' banned username'});

Just find the forbidden word that is included in the username. (res.json is part of Express which you might use for setting up a server)

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
2

Seems like you want to check if item is in username or not,

If username is an array (It seems to be array based on your previous question)

match = !!username.filter( s => item.indexOf(s) != -1 ).length;

or use some

match = username.some( s => item.indexOf(s) != -1 );

Note

I am using indexOf since it seems from your previous question you wanted to match owner123 with owner as well.

gurvinder372
  • 66,980
  • 10
  • 72
  • 94
2

This looks like you're looking for a match or submatch of the user name. Given the error message provided, a submatch doesn't seem to make sense, so I'll assume an exact match is actually needed.

If you do want a submatch, use the .includes() method on username

const username = "master";
const FORBIDDEN_USERNAME_LIST = ['admin', 'master', 'owner'];

const match = FORBIDDEN_USERNAME_LIST.some(n => n === username);

if (match) {
  console.log(username, 'exists');
}
  • 1
    @touchingtwist: Why do you think a regex is better than a much simpler text search using `.includes()` or `.indexOf()`? It'll be slower and can break depending on what characters are valid for your user names. –  Dec 27 '17 at 15:09
1

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');
}
SLePort
  • 15,211
  • 3
  • 34
  • 44