You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Write a function that checks if a given string is a valid username. A valid username should contain only alphanumeric characters and underscores, and should be between 4 and 16 characters long.
192
+
193
+
Write a function called `isValidUsername` that takes a string `username` in its parameter and returns true or false.
Write a function that checks if a given string is a valid username. A valid username should contain only alphanumeric characters and underscores, and should be between 4 and 16 characters long.
4
+
5
+
Write a function called `isValidUsername` that takes a string `username` in its parameter and returns true or false.
6
+
7
+
## Answer
8
+
9
+
```javascript
10
+
// Function to validate username
11
+
functionisValidUsername(username) {
12
+
// Regular expression pattern for username validation
13
+
constregex=/^[a-zA-Z0-9_]{4,16}$/;
14
+
15
+
// Test if the string matches the username pattern
16
+
returnregex.test(username);
17
+
}
18
+
```
19
+
20
+
## Answer Explanation
21
+
22
+
The `isValidUsername` function takes a string as input and uses a regular expression to check if it's a valid username. The regular expression `^[a-zA-Z0-9_]{4,16}$` is used to match the username pattern.
23
+
24
+
The test method is then used to check if the input string matches the regular expression, if it's a valid username function returns true otherwise false.
0 commit comments