A blog

A blog

Written by Ebenezer Mathebula | Published 3 months ago

Getting Started With RegEx

Let’s say that, if you want to find the word "help" in the string “God helps those who help themselves”, you can use the following regular expression (RegEx): /help/.

JavaScript uses the .test() method, which takes the RegEx and applies it to a string (placed inside parenthesis). It returns true or false, depending on whether the pattern matches or not.

let str1 = "God helps those who help themselves";
let str2 = "You can't expect everyone to like you";
let testRegex = /help/;
testRegex.test(str1); //returns true
testRegex.test(str2); //returns false

In the example above, we used a literal RegEx /help/ to search for the word help in variable str1 and str2.

Another example of literal RegEx can be /expect/, which will match the word expect from the string.

We can look for multiple patterns using the OR operator: |.

Example: if you wanted to match “hi”, “hello”, or “hola”, the RegEx would be: /hi|hello|hola/.

Match Method

There is another method in JavaScript: .match(). It is applied on a string and takes a RegEx as an argument. The .match() method returns an array with the matched RegEx. s

RELATED BLOGS