JavaScript regex program to display name to be only numbers, letters and underscore.

Following is the code to to display name to be only numbers, letters and underscore using regex 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;
   .result {
      font-size: 20px;
      font-weight: 500;
<h1>, letters and underscore only regex match</h1>
<div style="color: green;" class="result"></div>
<input type="text" class="txt" /&lgt;
<button class="Btn"&g;CHECK</button>
Click the above button to check if the text contains only numbers, letters
and underscore or not
   let resEle = document.querySelector(".result");
   document.querySelector(".Btn").addEventListener("click", () => {
      var str = document.querySelector(".txt").value;
      var regex = /^\w+$/;
      var match = str.match(regex);
      if (match) resEle.innerHTML = "The text entered is valid";
      else resEle.innerHTML = "The text enterd is not valid";


The above code will produce the following output −

On entering text having space between them and clicking on ‘CHECK’ −

On entering valid text and clicking on ‘CHECK’ −