JavaScript Regular Expressions

JavaScript Regular Expressions, a brief definition

It is a sequence of characters that creates a search pattern for text or strings. These patterns are useful to search for any kind of text, validate user input E.g emails, and find & replace strings.

The Syntax

The syntax is /pattern/modifiers;

/theString/i is a JavaScript regular expression. This expression will be used to find ‘theString‘.

Here /theString/ is a pattern and ” i ” is a modifier. This modifier is used for case-insensitive(find both upper and lower case strings).

We will explain modifiers later in this chapter.

// How to use JS Regular Expression

let testString= "This is a string to test JS regex.";

let searchedString = testString.match(/is/i);

console.log(searchedString);

//the match() method finds the specified string and returns the result as an array.


// Output: ["is", index: 2, input: "This is a string to test JS regex."]



//

How to use JavaScript Regular Expressions.

Regular Expressions are also objects in JavaScript. You can use them as follow.

Use With Methods of RegExp.

The RegExp methods include exec() and test()

Examples of RegExp method, test();

test() method searches a string for a pattern. If found then it returns true else return false.

// How to use js regular expression 

// test() method

let pattern = /sample/;

let wordFound = pattern.test("This is a sample string");

console.log(wordFound);

// Output: true



//

Example of RegExp method, exec();

The exec() method searches a string for a pattern. If found then it returns the specified text in an object otherwise it returns null.

// the RegExp method, exec();

let pattern = /sample/;

let wordFound = pattern.exec("This is a sample string");

console.log(wordFound);

// Output: ["sample", index: 10, input: "This is a sample string", groups: undefined]

//if the pattern not found then you will get null.
let pattern = /text/;

let wordFound = pattern.exec("This is a sample string");

console.log(wordFound);

//Output: null


//

Use With Methods of String.

The string methods includes match(), matchAll(), replace(), replaceAll(), search(), and split()

The string match(); method

The string match method find matches against the regular expression. If the flag ( g ) is available with regular expression as a modifier then this method returns all the matches otherwise it returns only the first occurrence.

Example of str.match(regexp) method

// Example of match(); method without any flag

let str = "I am learning JavaScript and Java language";

let result = str.match(/Java/);

console.log(result);
//Output: ["Java", index: 14, input: "I an learning JavaScript and Java language", groups: undefined]


// Example of match(); method with ' g ' flag
// this will return an array of all the matches against a specified pattern
let str = "I am learning JavaScript and Java language";

let result = str.match(/Java/g);

console.log(result);
//Output: ["Java", "Java"]

//

The string matchAll(); method

matchAll(regexp); returns an iterator containing all the matched strings against specified JavaScript Regular Expressions. You can use a loop to extract required data from this iterator.

If the result is empty the it returns empty array instead of null.

Example of string matchAll(); method.

Note: make sure it is necessary to set the flag ‘ /g ‘ as modifier otherwise, you will get a type error.

//Example of str.matchAll(); method

let regexp = /Java/g;

let sentence = 'I am learning JavaScript and Java';

let matches = sentence.matchAll(regexp);

for (let match of matches) {

  console.log(match[0]);
}

//Output: prints 'Java' two times.


//

The string replace(); method

The replace(); in JavaScript Regular Expressions simply replaces one value with another value in a string.

//Basic example of replace() method

let sentence = "I am learning JavaScript and C#";

let result = sentence.replace("C#", "C++");

console.log(result);

//Output: I am learning JavaScript and C++


//

However it also accepts regular expression and can replace the matched strings. For Example,

// JavaScript Regular Expressions, replace() method with RegExp

let sentence= "I am learning JavaScript frameworks";

let result = sentence.replace(/learning/, "working with");

console.log(result);

//Output: I am working with JavaScript frameworks

//

The JavaScript Regular Expressions made it powerful to search upper and lowercase strings at the same time. The case-insensitive feature is not available with plain text or strings.

The string replaceAll(); method

This method returns a new string with all the replacements in a string specified in the argument of replaceAll(); as RegExp or substring.

Note: while using JavaScript Regular Expressions you need to set the global flag (‘ /g ‘) otherwise, you will get a TypeError. It is similar to the matchAll();

// Example of replaceAll(); in JS

let sentence = 'I am learning Java, C# and C++';

const regex = /C/g;

console.log(sentence.replaceAll(regex, 'J'));
//Output: I am learning Java, J# and J++

//

The string search(); method

The search(); method searches for a specified value and returns the position of the match.

Consider the example with a substring.

// Example of search() method with substring


let sentence= "I am learning JavaScript frameworks";

let result = sentence.search("JavaScript");
// search 'JavaScript' in sentence.

console.log(result);
// position of 'JavaScript'.
//Output: 14



//

If you are using JavaScript Regular Expressions with search(regexp); then it will output the result in a similar way as mentioned above.

// Example of search() method with Regular Expression


let sentence= "I am learning JavaScript frameworks";

let result = sentence.search(/JavaScript/);
// search 'JavaScript' in sentence.

console.log(result);
// position of 'JavaScript'.
//Output: 14



//

The string split(); method

The split() method divides the string in to substrings and returns an array.

// Example of the split method, without RegExp


let sentence = "I am learning JavaScript frameworks";

let result = sentence.split(' ');
// split the string on the basis of whitespace

console.log(result);
// Output: ["I", "am", "learning", "JavaScript", "frameworks"]



// Example 2

let sentence = "I-am-learning-JavaScript-frameworks";

let result = sentence.split('-');
// split the string on the basis of -

console.log(result);
// Output: ["I", "am", "learning", "JavaScript", "frameworks"]

If you are using regular expression it split the string in same way.

// example of split() method with JavaScript regular expressions


let sentence = "I am learning JavaScript frameworks";

let result = sentence.split(/\s/);
// split the string on the basis of whitespace

console.log(result);
// Output: ["I", "am", "learning", "JavaScript", "frameworks"]



// Example 2

let sentence = "[email protected]";

let result = sentence.split(/\W|_/g);
// split the string on the basis of special characters

console.log(result);
// Output: ["I", "am", "learning", "JavaScript", "frameworks"]

Watch the video and learn JavaScript Regular Expressions

References

https://www.w3schools.com/js/js_regexp.asp

https://javascript.info/regular-expressions

https://www.freecodecamp.org/news/javascript-regex-match-example-how-to-use-the-js-replace-method-on-a-string/

Similar Posts