다음은 JavaScript에서 정규식을 사용하여 이름을 숫자, 문자 및 밑줄로만 표시하는 코드입니다. −
예시
<!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 {
font-size: 20px;
font-weight: 500;
}
</style>
</head>
<body>
<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>
<h3>
Click the above button to check if the text contains only numbers, letters
and underscore or not
</h3>
<script>
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";
});
</script>
</body>
</html> 출력
위의 코드는 다음 출력을 생성합니다 -

사이에 공백이 있는 텍스트를 입력하고 '확인'을 클릭하면 -

유효한 텍스트를 입력하고 '확인'을 클릭하면 -
