Regex

by black strings

HTML

<div class="input-container">
  <label for="pattern-input">Pattern</label>
  <input type='text' id='pattern-input'>
  
  <label for="test-input">Test</label>
  <input type='text' id='test-input'>
  <button id="confirmBtn">Test</button>
</div>




<div id="result">

</div>

CSS

body {
  background-color: #111111;
}
.input-container {
  display: inline-block;
  padding: 1rem;
  background-color: #2e2e2e;
  border-radius: .5rem;
}
.input-container input {
  margin-bottom: .5rem;
}
.input-container label {
  color: white;
  display: block;
  font-family: sans-serif;
  font-size: .8rem;
  letter-spacing: .05rem;
}
#result {
  color: grey;
}

JavaScript

// 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');
}