// test() is faster but you'll need to call it on a RegEx object
// if you only need boolean and not substrings, use test()
// match can be called on the string object
// * for faster realtime testing of regex against multiple patterns visit https://regex101.com/
// quick recap
// ^ start with
// [ ] group into one character
// a-z range
// * array of rule
// $ ends with
// for includomg space just put a space
// \d{5} expect 5 instance of numbers
// \w word so same as [a-zA-Z0-9_]
// ie.
// basic date pattern: 01/11/2022 > \d{2}/\d{2}/\d{4}
function test(){
// any letters and numbers and space, but exlcude all special characters
var patternToMatch = '^[a-zA-Z0-9 ]*$';
// explicit way but has more params you can enter in easier
var reg = new RegExp();
var matchesPattern = reg.test('abc def');
// alternative shorter way without having to explicitly new up the regex object
//var regex = /^[a-zA-Z0-9 ]*$/;
//matchesPattern = regex.test('abc def');
console.log(matchesPattern);
return matchesPattern;
}
function exectuteTest(pattern, value) {
if(pattern && value) {
try {
const reg = new RegExp(pattern);
const matchesPattern = reg.test(value);
return matchesPattern;
} catch(e) {
console.error(e.message);
return false;
}
}
console.error('empty inputs');
return false;
}
function getPatternAndTestInputs() {
const patternInput = document.getElementById('pattern-input');
const testInput = document.getElementById('test-input');
return {pattern: patternInput.value, test: testInput.value}
}
var btn = document.getElementById('confirmBtn');
var resultDom = document.getElementById('result');
if(btn) {
btn.addEventListener('click', () => {
//const result = test();
const values = getPatternAndTestInputs();
const result = exectuteTest(values.pattern, values.test);
resultDom.innerHTML = result;
});
} else {
console.error('btn click not setup');
}
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.