JSFiddle - React, Tailwind, and code Playground
by Phil Everton
HTML
<h2>Bulky Regex</h2>
<input value="" type="text" id="bulk"/>
<span id="info"></span>
<h2>Wrikken's regex</h2>
<input value="" type="text" id="wrik"/>
CSS
body{font-family:sans-serif}
input{font-size:120%;padding:10px;border:3px solid #CCCCCC}
input:active,input:focus{border-color:#666666}
h2{margin-bottom:0}
#info{font-size:70%}
JavaScript
//this should only allow input of numbers, 'tx' or 'na'
//http://stackoverflow.com/questions/19550026/limiting-a-textbox-to-digits-or-one-of-two-non-repeating-strings-only-using-regu/
//this works, but is bulky and doesn't use the potential of regex
$('#bulk').keyup(function () {
var a = $(this).val();
var info = '';
if (a.match(/^tx/)) {
a = 'tx'; //set manually
info = a;
} else if (a.match(/^na/)) {
a = 'na'; //set manually
info = a;
} else if (a.match(/[\d]/)) {
a = a.replace(/[^0-9]+/g, ''); //replace all but numbers
info = 'numbers!';
} else if (a.match(/^[nt]/)) {
a = a.replace(/^([tn])([a-zA-Z])+$/, '$1'); //replace with first letter
info = 'need a tx or na here...';
} else {
a = ''; //matches nothing equals nothing
info = 'nope';
}
$(this).val(a); //print new value
$('#info').html(info);
})
//this works, and is an awesome example of regex
$('#wrik').keyup(function () {
var a = $(this).val(); //get current value
$(this).val(a.replace(/^(n(a?|$)|t(x?|$)|[0-9]*).*$/g, '$1')); //print new value using Wrikken's regex
});