Regular expressions allow for pattern searching on string data. This example demonstrates a search for strings on one or more digits in sequence. The first example finds only the first multiple digit pattern. The second global version, with the added g, can be used repeatedly to find successive locations as demonstrated below.
<!DOCTYPE html> <html> <head> <title>XoaX.net's Javascript</title> <script type="text/javascript" src="ASimpleRegularExpression.js"></script> </head> <body onload="Initialize()"> </body> </html>
function Initialize() { const ksText = 'Matthew 12:39 - An evil and adulterous generation seeks for a sign; but no sign shall be given to it except the sign of the prophet Jonah.'; // Matches one or more digits const kqRegExDigits = /\d+/; var bFound = kqRegExDigits.test(ksText); document.writeln("<h1>test() on /\d+/</h1>"); document.writeln("Digits " + (bFound ? "were" : "were not") + " found in<br /><b>"+ksText+"</b><br /><br />"); var qResult = kqRegExDigits.exec(ksText); document.writeln("<h1>exec() on /\d+/</h1>"); document.writeln("Search for digits in<br /><b>"+ksText+"</b><br /> gives this result: "+ qResult+"<br />"); document.writeln("<h1>The object returned from exec() on /\d+/</h1>"); document.writeln("The complete object that is returned:<br />"); PrintAnObject(qResult); document.writeln("<br />"); // Add g to make the search "global" meaning that it can be applied repeatedly to get the next location const kqRegExDigitsGlobal = /\d+/g; document.writeln("<h1>Repeated calls to exec() on /\d+/g</h1>"); qResult = kqRegExDigitsGlobal.exec(ksText); document.writeln("Search for digits in<br /><b>"+ksText+"</b><br /> gives this result: "+ qResult+"<br />"); document.writeln("Last Index = "+kqRegExDigitsGlobal.lastIndex+"<br />"); qResult = kqRegExDigitsGlobal.exec(ksText); document.writeln("Search for digits in<br /><b>"+ksText+"</b><br /> gives this result: "+ qResult+"<br />"); document.writeln("Last Index = "+kqRegExDigitsGlobal.lastIndex+"<br />"); qResult = kqRegExDigitsGlobal.exec(ksText); document.writeln("Search for digits in<br /><b>"+ksText+"</b><br /> gives this result: "+ qResult+"<br />"); document.writeln("Last Index = "+kqRegExDigitsGlobal.lastIndex+"<br />"); } function PrintAnObject(qObject) { var iCount = 0; var sOutput = typeof(qObject)+": " + qObject.constructor.name + "<br />"; for (var sProperty in qObject) { sOutput += " " + sProperty + ': ' + qObject[sProperty]+"<br />"; ++iCount; // Truncate if there are too many properties if (iCount >= 15) { document.writeln(sOutput); document.writeln(" ...<br />"); return; } } document.writeln(sOutput); }
© 20072025 XoaX.net LLC. All rights reserved.