Developers have been using text editors for a long time. And like most tools, all text editors have one feature in common: find and replace.

If you have been using find and replace for a while, you might know how useful this feature is. But most of us don’t know that this tool is even more powerful than we realize.

It can not only replace plain strings, but patterns too. These patterns are known as Regular Expressions.

Regular expressions exist in JavaScript and most other programming languages. Regex (for short) are a very powerful tool to help you find simple as well as complex search patterns.

String-searching algorithms are also a significant branch of computer science. In this article we will learn how to use this amazing tool in JavaScript.

Why Regular Expressions?

You won’t understand the real importance of Regular expressions until you are given a long document and are told to extract all emails from it.

You could do that manually, but there is a super fast method that can do it for you. Most modern text editors allow Regex in their Find option. It is usually denoted by .*.

Extracting Emails using Regex

And that’s not all regex can do – emails are just an example. You could search any type of string that follows a pattern, for example URLs or text between parentheses.

Regex can also be used to validate certain types of patterns, like validating Email. You could replace some long validation logic like this:

function IsValidEmail(email) {
        if (email.length <= 2) {
            return false;
        }

        if (email.indexOf("@") == -1) {
            return false;
        }

        var parts = email.split("@");
        var dot = parts[1].indexOf(".");
        var len = parts[1].length;
        var dotSplits = parts[1].split(".");
        var dotCount = dotSplits.length - 1;

        if (dot == -1 || dot < 2 || dotCount > 2) {
            return false;
        }

        for (var i = 0; i < dotSplits.length; i++) {
            if (dotSplits[i].length == 0) {
                return false;
            }
        }

        return true;
    };

#javascript #regex #developer #string

JavaScript Regex Match Example – How to Use JS Replace on a String
2.55 GEEK