Regex for Twitter Username in JavaScript

On my previous post, I discussed how to validate Twitter username in PHP using Regular Expression (regex). As my project required me to perform the validation on both the client and server side, I had to come up with a JavaScript solution to validate the Twitter username. So, I created a function within an external JavaScript file and included it with the html document to check the user inputs whenever I need it.

Now, this is how the validity testing method works.

   var username = "twitterUser";
   var expr = /^[A-Za-z0-9_]{1,15}$/;

As you can see from the snippet, I am using .test() method to check against the string (username) provided by the user. The literal regular expression is exactly the same as I mentioned on my previous post. The test result will be alerted on this case but you can return the response to the script back and move on with handling the rest of the process accordingly.

One of the primary reason why I am using .test() method over .match() is because .test method provides a boolean (true/false) response. On the contrary .match method returns the full string back if it matches with the expression otherwise it would simply return null which is a bit inconvenient for me.

Trust me there are lots of different opinion over this issue but I decided to move on with .test method regardless. We already learned from jsPerf site’s test result that .test method performs significantly faster over .match on almost all the web browser. So, there shouldn’t be any question on this aftewards.

Today In History



Leave a Reply

Note: Convet HTML, PHP, JavaScripts from HTMLify, before posting from comment section.
License: By submitting a comment here you grant this site a perpetual license to reproduce your words and name/Web site in attribution. Please use your real name or a pseudonym (i.e., pen name, alias, nom de plume) when commenting. If you add your site name, company name, or something completely random, I'll likely change it to whatever I want.