JavaScript Regular Expressions

Regular expressions are a string of characters describing a search pattern. This search pattern is then used to specify what we are searching in a text.

Following is the code for regular expressions in JavaScript −


 Live Demo

<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
      font-size: 18px;
      font-weight: 500;
<h1>JavaScript Regular Expressions</h1>
<div class="sample">The king bought the ring and went to the palace.</div>
<div style='color:black' class="result"></div>
<button class="Btn">CLICK HERE</button>
Click on the above button to replace king with queen in the text above
   let sampleEle = document.querySelector('.sample');
   let resultEle = document.querySelector('.result');
      let newText = sampleEle.innerHTML.replace(/king/gi,'queen');
      resultEle.innerHTML = 'Result = ' + newText;


The above code will produce the following output -

On clicking the ‘CLICK HERE’ button −