JSFiddle - React, Tailwind, and code Playground
by lid0
HTML
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.7.0/moment.js"></script>
<h3>Live User - Test Console<br></h3>
<pre>
You can try different variations (with space or without, full names of units or short, plural or singular
you may repeat unit if addOnRepeat is on.
<hr>
1d10h60m
1 day
5 days 6h
5d6hours1minute
</pre>
<br>
<input id="live" value="1week 2 days 24hours 60minutes" ></input> view update below as you type<br>
Options <input id="addOnRepeat" type="checkbox" checked value="addOnRepeat" title="repeating units are allowed and will be summed up, for example: 1d 2d will return 3days" />addOnRepeat</input>
<input id="failOnRepeat" type="checkbox" value="failOnRepeat" title="fail if repeating units are detected, addOnRepeat must be off"/>failOnRepeat</input>
<pre id="live_result"></pre>
<hr><br>
<pre id="a"></pre>
CSS
#live {
width: 300px;
padding:4px;
background:#cfc;
}
#live_result {
background-color:#E0FFE2;
padding:5px;
}
JavaScript
/** Author Lidlanca **/
//dependency moment.js, jquery.js
/**
@Description
This is an Helper: convert list
d,M,h,w,m,day,month,hour,week,minute
to
(day[s]?|month[s]?|hour[s]?|week[s]?|minute[s]?|[dMhwm]{1})
when filter is activate on parseTime() function it will construct a full regex expression
/([0-9]{1,}\s{0,})(day[s]?|month[s]?|hour[s]?|week[s]?|minute[s]?|[dMhwm]{1})/g
To capture the numeric unit
All words input as singular, dum plural support is automatically added.
All chars are treated as literal, using the custom escape() function
@param str String input letters or words with , delimiter"
@param subgroup Bool subgroup word and letter match for future detection; default false;
@return String
**/
function allowedWordOrLetterToRegExpGroup(str_in, subgroup) {
function escape(i) { //escape any none alphanumeric
return i.replace(/[^A-z0-9,]/g, function (match) {
return ("\\" + match); //add escape char to match
});
}
var items = str_in.split(",");
var letter = "";
var word = [];
for (var s in items) {
if (items[s].length <= 1) {
letter += escape(items[s]);
//letter+=items[s];
} else {
word.push(escape(items[s]) + "[s]?"); // add "[s]?" to allow generic plural form
//word.push(items[s]);
}
}
if (subgroup) { //add subgroup to words and letter match
lt = "";
if (letter.length > 0) lt = ")|([" + letter + "]{1})";
return "((" + word.join("|") + lt + ")";
} else {
if (letter.length > 0) word.push("[" + letter + "]{1}"); //push letter to word array so we can join with |
return "(" + word.join("|") + ")";
}
}
//----------------------------------------------------------------------
/**
return an object understood by moment.duration
**/
function parseTime(humanTime, options) {
var cons = {
DAY: "d,day",
MONTH: "month,M",
HOUR: "hour,h",
WEEK:...