Limiting the contents of a string via RegEx

Often, you will need to prevent users from entering data that doesn’t conform to a specific pattern. For example, you may want to allow users to enter only numbers or only valid email addresses. To this end, I’ve written a little utility function that returns the “standardised” version of a string, according to the regex you supply.

[sourcecode language=”javascript”]String.implement({
limitContent: function(allowedRegex) {
return $splat(this.match(allowedRegex)).join(”);
}
});[/sourcecode]

Basically, the function takes the result of evaluating the regular expression on the string, converts it into an array if it isn’t one, and then joins the array’s elements together with an empty string.

Examples:

[sourcecode language=”javascript”]console.log(“12345”.limitContent(/.{4}/)); // Only allow four characters
console.log(“joe@mail.com”.limitContent(/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}/)); // Only allow email addresses
[/sourcecode]

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

To respond on your own website, enter the URL of your response which should contain a link to this post’s permalink URL. Your response will then appear (possibly after moderation) on this page. Want to update or remove your response? Update or delete your post and re-enter your post’s URL again. (Find out more about Webmentions.)