JavaScript code to extract the words in quotations

JavascriptWeb DevelopmentObject Oriented Programming

Following is the code to extract the words in quotations using JavaScript −

Example

 Live Demo

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result,.sample {
      font-size: 20px;
      font-weight: 500;
      color: red;
   }
</style>
</head>
<body>
<h1>Extract the words in quotations</h1>
<div style="color: green;" class="result">Hello "World"</div>
<div class="sample"></div>
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to get the text between quotes</h3>
<script>
   let resEle = document.querySelector(".result");
   let BtnEle = document.querySelector(".Btn");
   let sampleEle = document.querySelector(".sample");
   let regex = /"(.*?)"/g;
   var match = regex.exec(resEle.innerHTML);
   BtnEle.addEventListener("click", () => {
      if (match) {
         sampleEle.innerHTML += match[0];
      }
   });
</script>
</body>
</html>

Output

The above code will produce the following output −

On clicking the ‘CLICK HERE’ button −

raja
Published on 18-Jul-2020 07:14:05
Advertisements