JavaScript Introduction | Regular Expressions | Basic Concepts

Creating Regular Expressions

In JavaScript, regular expressions can be created in the following ways.

  1. Create one with a regular expression literal.
  2. Create one with a RegExp object.

In JavaScript, a regular expression literal is written with the following syntax.

Syntax

/searchPattern/flags

A regular expression literal starts with a slash (/) and ends with a slash (/). You can also add flags as needed to change the default search settings.

var regStr = /a+bc/;             // Created with a regular expression literal
var regObj = new RegExp("a+bc"); // Created with a RegExp object
regStr;                          // /a+bc/
regObj;                          // /a+bc/

When you want to search for a simple pattern with a regular expression, you can directly list the string you want to find.

For example, the following regular expression matches only the exact string "abc".

/abc/

The following example shows a simple pattern search using regular expressions.

var targetStr = "Soy sauce factory manager Kang and soybean paste factory manager Jang."
var strReg1 = /factory/;
var strReg2 = /managerK/;

targetStr.search(strReg1); // 10
targetStr.search(strReg2); // -1

In the example above, the first regular expression matches the substring "factory" in the target string. However, the search() method returns only the index of the first matching string.

In the example above, the second regular expression does not match anything because the target string does not include the exact substring "managerK". If the search() method cannot find a substring in the target string that matches the regular expression passed as an argument, it returns -1.

The search() method is a JavaScript String method that returns the position of the first string in the target string that matches the regular expression passed as an argument.

Flags

When creating a regular expression, you can use flags to change the default search settings. Flags set this way cannot be added or removed later.

Flag Description
i Makes pattern matching case-insensitive.
g Selects all matching parts when comparing the search pattern.
m Compares multiline input strings as multiple lines.
y Starts comparison from the current position in the target string.
var targetStr = "bcabcAB";
var strReg = /AB/;              // By default, search pattern comparison is case-sensitive.
var strUsingFlag = /AB/i;       // Same as new RegExp("AB", "i").
targetStr.search(strReg);       // 5
targetStr.search(strUsingFlag); // 2 -> Searches without distinguishing uppercase and lowercase.