Regex in JavaScript
Regular expressions are often referred to as Regex or Regexp. It is a very powerful tool that helps developer to work with strings or text. They are popularly used as pattern-Matching tools which help to search and manipulate specific strings or text.
Regex is so powerful that we can use regex to match specific characters, words, and even the entire string of text documents. They are most commonly used in text editors, and programming languages for tasks such as search, replace, and data validation.
Regex patterns are made up of a combination of characters and special symbols. The most basic regex pattern is a simple string of characters. For example, the pattern "hello" would match the string "hello" in a text document.
Some of the most common uses cases of a regex are:
Search and Replace: We can use regex to search for a specific pattern in text documents. And replace it with another pattern. This is often used in text editors , and programming language to make changes to a document.
Data Validation: Regex can be used to ensure that a specific string of text conforms to a certain pattern, such as an email address or phone number.
Data Cleaning: Regex can be used to clean up messy data, such as removing unwanted or characters or converting text to a consistent format.
The basic structure of regex has the following parts.
An opening tag
A closing tag.
The pattern.
The flag.
Here some code are related to the Regex.
let pattern='pw'
let flag= 'gi' // g = gobal matching and
//i = case-insensitive {uppercase and lowercase letter}
let regExone= new RegExp(pattern, flag)
// let flag= 'gi'
// let regExTwo=new RegExp(pattern,flag)
let regExThree=/pw/gi
const strTocheck="PW is growing at a rapid speed and recently they are working on Pwskills to create skills based pwcontent"
const result= regExThree.test(strTocheck)
// console.log(result);
const anotherResult=strTocheck.match(regExThree)
// console.log(anotherResult);
const oneMoreResult=strTocheck.replace(regExThree,'p-w')
// console.log(oneMoreResult);
const webUrl="https://pwskills.com/shushil%20chaubey"
const useableUrl=webUrl.replace(/%\d0/, '-')
// console.log(useableUrl);
let string="PW Skills is the best educational platform to learn from ";
// let pattern1=/PW Skills/;
// let pattern1=/PW Skills/i
let pattern1=/PW Skills/g
console.log(pattern1.test(string));
console.log(string.match(pattern1));
// find number in the string
let string1="The numbers are : 1 2 3 4 5 6"
let pattern2=/[1-5]/g
console.log(string1.match(pattern2));