JSFiddle - React, Tailwind, and code Playground
by mjmitche
HTML
<h1>Using the match() function</h1>
<p id="sourceText">To get in touch with me, try calling me at 555-1212. If
that doesn't work, try calling my cell phone at 555-1234. Finally, try
faxing me at 555-6789. Otherwise, just send me an email.</p>
<form method="post">
<input name="Button1" type="button" value="Global Match" id="btnMatchGlobal"/>
<input name="Button2" type="button" value="Non-Global Match" id="btnMatchNonGlobal"/></form>
JavaScript
function findMatchesGlobal(sourceString, patternToFind) {
var result = sourceString.match(patternToFind);
alert("Found a total of " + result.length + " matches: " + result.join(", "));
}
function findMatchesNonGlobal(sourceString, patternToFind) {
var result = sourceString.match(patternToFind);
alert("Found a match: " + result[0] + "\nThe exchange part was: " + result[1] + "\nThe rest of the number was: " + result[2]);
}
function doGlobalMatch() {
findMatchesGlobal(document.getElementById('sourceText').innerHTML,/(\d{3})-(\d{4})/g);
}
function doNonGlobalMatch() {
findMatchesNonGlobal(document.getElementById('sourceText').innerHTML,/(\d{3})-(\d{4})/);
}
window.onload = function() {
document.getElementById('btnMatchGlobal').onclick = doGlobalMatch;
document.getElementById('btnMatchNonGlobal').onclick = doNonGlobalMatch;
}