Skip to content

Instantly share code, notes, and snippets.

@classmember
Last active November 13, 2018 19:29
Show Gist options
  • Select an option

  • Save classmember/46a85ba142c8868d6230186d1a1f2f99 to your computer and use it in GitHub Desktop.

Select an option

Save classmember/46a85ba142c8868d6230186d1a1f2f99 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<body>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet">
<style>
h1,h2,h3,h4,h5,h6,p,label,input {font-family: 'Lato', sans-serif;}
body {padding: 2rem;}
</style>
</head>
<h2>Javascript: find number of matches</h2>
<p>Use the String and Regex inputs to test for the number of matches.</p>
<form>
<label>String: </label><br>
<input id="string_input" input type="text" name="string_input" value="The best things in life are free">
</input>
<br><br>
<label>Regex: </label><br>
<input id="regex_input" input type="text" name="regex_input" value="e">
</input>
<br><br>
<label>Number of matches: </label><br>
<input id="number_of_matches" input type="text" name="number_of_matches" readonly>
<p id="demo"></p>
</form>
<script>
function main() {
add_listeners();
check_regex();
}
window.onload = main;
var timer_to_check_regex = setInterval(check_regex, 100);
function add_listeners() {
document.getElementById("string_input")
.addEventListener("change", check_regex);
document.getElementById("regex_input")
.addEventListener("change", check_regex);
}
function check_regex() {
var str = document.getElementById("string_input");
var rgx = document.getElementById("regex_input");
var re = new RegExp((rgx.value || '\\u0000'), 'g');
var num_matched = document.getElementById("number_of_matches");
var result = (str.value.match(re) || []).length;
num_matched.value = result;
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment