Broad Network


ECMAScript String Regular Expression Methods

Advanced ECMAScript Regular Expressions – Part 1

Foreword: In this part of the series I talk about the ECMAScript regular expression methods, which are: search(),match(),replace(), and split().

By: Chrysanthus Date Published: 22 Sep 2014

Introduction

This is part 1 of my series, Advanced ECMAScript Regular Expressions. In this part of the series I talk about the ECMAScript regular expression methods, which are: search(),match(),replace(), and split().

Note: If you cannot see the code or if you think anything is missing (broken link, image absent), just contact me at forchatrans@yahoo.com. That is, contact me for the slightest problem you have about what you are reading.

Pre-Knowledge
Every computer language builds up as you learn. You need to learn something today in the language, and then use it to learn something at a higher level in the same language, tomorrow. This series is part of my volume, ECMAScript Course. At the bottom of this page, you have links to the different series you should have read before reaching here.

True and False Equivalents in ECMAScript
Before we look at the methods, let us first see what is equivalent to true and what is equivalent to false in ECMAScript. You need this knowledge in order to write flexible code for regular expressions.

0 is false, any other number, be it positive or negative is true. So –2 and +2 (or 2) are true. undefined is false. A string with content is true. An empty string is false. Note: "" is an empty string, but " " is not an empty string because it has a space character.

The search Method
The syntax is:

    stringObject.search(regexp)

This method searches the whole string. There may be more than one occurrence of the match. It is the index of the first character of the first occurrence of the match that is returned. If the substring is not found, -1 is returned. Read and try the following code

<!DOCTYPE HTML>
<html>
<head>
</head>
<body>

    <script type="text/ECMAScript">

        strObj = new String("The world is round; the world is big.");

        regex = /w.rld/

        indx = strObj.search(regex);

        alert(indx);

    </script>

</body>
</html>

The extra HTML code is to produce a web page. The output is 4 for the w in the first “world” in the string. Remember, index counting begins from zero.

Also remember, the string (or string literal) being searched is called the subject.

The match Method
The match method is similar to the search method by searching the whole string, and matching the first occurrence of the substring. However, if the substring is found, the found substring is returned; if the substring is not found, null is returned. The syntax is:

    stringObject.match(regex)

Read and try the following code, where the first code segment sees the first substring occurrence and the second code segment sees nothing:

    <script type="text/ECMAScript">

        strObj = new String("The world is round; the world is big.");
        ret = strObj.match(/w.rld/);
        alert(ret);

        strObj = new String("The world is round; the world is big.");
        ret = strObj.match(/werld/);
        alert(ret);

    </script>

The output gives “world” followed by null.

The replace Method
The replace() method actually does search and replace. It is similar to the search() method by searching the whole string and matching the first occurrence of the substring. When it sees a match, it returns the whole string with the replacement. When it does not see a match it still returns the whole string but without replacement. The syntax is:

    stringObject.replace (searchValue, replaceValue)

replaceValue is the substring for replacement; if absent, the value, undefined is the default argument and is used for replacement. Of course, searchValue is the substring searched. Read and try the following code:

    <script type="text/ECMAScript">

        strObj = new String("The world is round; the world is big.");
        ret = strObj.replace(/w.rld/, "ball");
        document.write(ret); document.write('<br>');

        strObj = new String("The world is round; the world is big.");
        ret = strObj.replace(/werld/, "ball");
        document.write(ret); document.write('<br>');

        strObj = new String("The world is round; the world is big.");
        ret = strObj.replace(/w.rld/);
        document.write(ret);

    </script>

The output is:

The ball is round; the world is big.
The world is round; the world is big.
The undefined is round; the world is big.

The split Method
The string object has a method called the split() method. This method splits the string (subject) into an array of sub strings. This is the syntax:

    arr = stringObject.split([separator][,limit])

The subject (stringObject) is the string to be split. It is not changed after the split. The separator is a regex. The array contains the substrings separated. The limit is an integer. Some strings (subjects) may have characters at their end that you do not need. If you know the number of substrings in the subject that you want, beginning from the left, you can type this number as the limit. Any substring after this limit will not go into the array. Both the limit and the separator are optional. In the example below, I do not use the limit.

Consider the following subject string:

    subject = "one two three";

If we know the regex (pattern) to identify space between words, then we can split this string into an array made up of the words, “one”, “two” and “three”.   is the character for a space. + will match a space, one or more times. The pattern to separate the above words is

               +

We assume that a space might be created by pressing the spacebar more than once. The following code illustrates the use of the split method with this pattern.

        <script type="text/ECMAScript">
            var subject = "one two three";

            var arr = subject.split(/ +/);

            alert(arr[0]);
            alert(arr[1]);
            alert(arr[2]);
            alert(subject);
        </script>

In the subject string the words are separated by spaces. The output of the above code is:

one
two
three

one two three

The spilt method has split the words in the subject string using the space between the words, and put each word as an element in the returned array. The last line in the output is not part of the array. In the code, the last alert statement displays the subject. This was done to show you that the subject remains unchanged after splitting. The word, “split” is not really proper in this section, since the subject string remains unchanged; however, that is the vocabulary the ECMAScript specification uses. If we wanted just “one” and “two”, the limit would have been 2.

It is possible to have words in a string separated by a comma and a space, as in

var subject = "one, two, three";

The regex to separate these words is:

          /, +/

The following code illustrates this:


        <script type="text/ECMAScript">
           subject = "one, two, three";

           arr = subject.split(/, +/);

           alert(arr[0]);
           alert(arr[1]);
           alert(arr[2]);
           alert(subject);
        </script>

The output of the above code is:

one
two
three

one, two, three

That is it for this part of the series. We stop here and continue in the next part.

Chrys

Related Links

ECMAScript Basics
ECMAScript Operators
Expressions in ECMAScript
Statements in ECMAScript
Custom Objects in ECMAScript
Functions in ECMAScript
ECMAScript Date Object
The ECMAScript String Object
ECMAScript String Regular Expressions
ECMAScript Template Literal
The ECMAScript Array
ECMAScript Sets and Maps
ECMAScript Number
Scopes in ECMAScript
Mastering the ECMAScript (JavaScript) eval Function
Sending Email with ECMAScript
ECMAScript Insecurities and Prevention
Advanced Course
Advanced ECMAScript Regular Expressions
Promise in ECMAScript 2015
Generator in ECMAScript 2015
ECMAScript Module
More Related Links
Node Mailsend
EMySQL API
Node.js Web Development Course
Major in Website Design
Low Level Programming - Writing ECMAScript Module
ECMAScript Course

NEXT

Comments

Become the Writer's Fan
Send the Writer a Message