Understanding Regular Expressions: A Beginner's Guide (Part 1)

Understanding Regular Expressions: A Beginner's Guide (Part 1)

In this article, we'll explore regular expressions, how to create regular expressions and what are the regex methods. So, let's dive in!

Introduction

Regular expressions, also known as "regex" or "regexp," are patterns that aid programmers in finding, searching, and replacing text. Despite being highly effective, regular expressions can be challenging to comprehend as they employ special characters to enable complex and flexible matches. In JavaScript, regular expressions are objects.

Creating a regular expression

Using a regular expression literal

const re = /ab+c/;

  • Consists of a pattern enclosed between slashes.

  • provide a compilation of the regular expression when the script is loaded.

  • If it remains constant, using this can improve performance.

Calling the constructor function of the RegExp object

const re = new RegExp("ab+c");

  • Provides a runtime compilation of the regular expression.

  • Use it when you know the regular expression pattern will be changing, or you don't know the pattern and are getting it from another source, such as user input.

Methods

Using the Test Method

Use test() whenever you want to know whether a pattern is found in a string. test() returns a boolean, unlike thesearch() method (which returns the index of a match, or -1 if not found).

Notice that quote marks are not required within the regular expression. Returns true if there is a match; falseotherwise.

let testStr = "The dog chased the cat"; 

let testRegex = /the/; 

testRegex.test(testStr);

//output: true

Extract Matches

the .match() method extracts the actual matches you found. If you don't give any parameters and use the match() method directly, you will get an Array with an empty string: [""].

"Hello, World!".match(/Hello/);
let ourStr = "Regular expressions";
let ourRegex = /expressions/;
ourStr.match(ourRegex);
/*Here the first match would return ["Hello"] and the second would return ["expressions"].*/

Note that the .match() syntax is the "opposite" of the .test() method.

'string'.match(/regex/);

/regex/.test('string');

Extract all matches

The matchAll() method returns an iterator of all results matching a string against a regular expression, including capturing groups.

const regexp = /t(e)(st(\\d?))/g;
const str = 'test1testing1'
const array = [...str.matchAll(regexp)];
console.log(array[0]);
// output: Array ["test1", "e", "st1", "1"]
console.log(array[1]);
// output: Array ["test", "e", "st", ""]

Search a string

The search() method tests for a match in a string. It returns the index of the match, or -1 if the search fails.

const paragraph = 'Can i do it?';
const regex = /i/;
console.log(paragraph.search(regex));
// output: 4
console.log(paragraph[paragraph.search(regex)]);
// output: "i"

Search and replace a match

The replace() method returns a new string with one, some, or all matches of a pattern replaced by a replacement. If the pattern is a string, only the first occurrence will be replaced. The original string is left unchanged.

You can search and replace text in a string using .replace() on a string. The inputs for .replace() are first the regex pattern you want to search for and second the string to replace the match or a function to do something.

let silverText = "The sky is silver.";
let silverRegex = /silver/;
console.log(silverText.replace(silverRegex, "blue"));
//output: The sky is blue.

Search for all matches and replace it

The replaceAll() method returns a new string with all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match. The original string is left unchanged.

Unlike replace(), this method would replace all occurrences of a string, not just the first one. This is especially useful if the string is not statically known, as calling the RegExp() constructor without escaping special characters may unintentionally change its semantics.

const p = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?';

console.log(p.replaceAll('dog', 'monkey'));
// output: "The quick brown fox jumps over the lazy monkey. If the monkey reacted, was it really lazy?"

const p = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?';
console.log(p.replace('dog', 'monkey'));
// output: "The quick brown fox jumps over the lazy monkey. If the dog reacted, was it really lazy?"

The exec() method executes a search for a match in a specified string.

If the match fails, the exec() method returns null and sets the regex's lastIndex to 0.

If the match succeeds, the exec() method returns an array and updates the lastIndex property of the regular expression object. The returned array has the matched text as the first item, and then one item for each capturing group of the matched text.

const regexH = RegExp('he*', 'g');
const str = 'hello, how are you doing?';
let array1;

while ((arrayHe = regexH.exec(str)) !== null) {
  console.log(`Found ${arrayHe[0]}. Next starts at ${regexH.lastIndex}.`);
  // output: "Found he. Next starts at 2."
  // output: "Found h. Next starts at 8."
}

Split a string

The split() method takes a pattern and divides a String into an ordered list of substrings by searching for the pattern, puts these substrings into an array, and returns the array.

const monthsString = "Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec";

const monthString = monthsString.split(',');
console.log(monthString);

// output:  Array ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]

Conclusion

  • If you need to know if a string matches a regular expression, use the test() method.

  • if you want to divide a long paragraph/string into smaller ones, use the split() method.

  • if you want to know whether a pattern is found, and also know its index within a string, use search().

  • if you want to extract the result of matching a string, use The match() method.

  • if you need to return a new string with a change without changing the original string, use the replace() method.

  • if you want to replace all occurrences of a string, not just the first one, use the replaceAll() method.

  • If you only want the first match found, you might want to use the exec() method instead.

  • If you want to obtain capture groups and the global flag is set, you need to use the exec() method or thematchAll() method instead.


Thank you for your time. I hope you found it useful. ❤️

If you enjoyed this article and want to be the first to know when I post the next part, you can follow me on Twitter @habibawael02 or here at Habiba Wael.