JSFiddle - React, Tailwind, and code Playground
HTML
Regex: <br/><input id="reg" value="^fo+(\s*b\S[rz])+$"><br/>
Test: <br/><input id="test" placeholder="string to test">
<span id="result"></span>
<pre id="promising"></pre>
<span class="note">Note that any regex without ^ on beginning is always promising</span>
CSS
body * {
margin: 20px 0;
}
body {
font-family: Courier;
}
pre, #result, .note {
border: 1px dashed gray;
padding: 5px;
overflow-x: auto;
vertical-align: middle;
}
input {
border: 2px solid gray;
vertical-align: middle;
padding: 5px;
font-family: Courier;
}
.note {
opacity: 0.5;
font-size: 0.7em;
margin-top:50px;
display: inline-block;
}
JavaScript
RegExp.prototype.promising = function(){
var source = this.source;
var regexps = {
replaceCandidates : /(\{[\d,]+\})|(\[[\w-]+\])|((?:\\\w))|([\w\s-])/g, //parts of regexp that may be replaced
dontReplace : /\{[\d,]+\}/g, //dont replace those
}
source = source.replace(regexps.replaceCandidates, function(n){
if ( regexps.dontReplace.test(n) ) return n;
return "(?:" + n + "|$)";
});
source = source.replace(/\s/g, function(s){
return "(?:" + s + "|$)";
});
return new RegExp(source);
}
var oryginalRegex = new RegExp($("#reg").val());
var promisingRegex = oryginalRegex.promising();
$("#reg").keyup(function(){
oryginalRegex = new RegExp( $(this).val() );
promisingRegex = oryginalRegex.promising();
$("#promising").text("MODIFIED REGEX: " + promisingRegex.source);
$("#test").keyup();
}).keyup();
$("#test").keyup(function(){
var val = $(this).val();
if ( !val ) {
$("#result").text("ENTER VALUE");
} else if ( oryginalRegex.test(val) ) {
$("#result").text("MATCH");
} else if ( promisingRegex.test(val) ) {
$("#result").text("PROMISING");
} else {
$("#result").text("BAD");
}
}).keyup();