// Util function
function addFormatter(input, formatFn) {
let oldValue = input.value;
const handleInput = event => {
const result = formatFn(input.value, oldValue, event);
if (typeof result === 'string') {
input.value = result;
}
oldValue = input.value;
}
handleInput();
input.addEventListener("input", handleInput);
}
// Example implementation
// HOF returning regex prefix formatter
function regexPrefix(regex, prefix) {
return (newValue, oldValue) => regex.test(newValue) ? newValue : (newValue ? oldValue : prefix);
}
// Apply formatter
const input = document.getElementById('user_login');
addFormatter(input, regexPrefix(/mysite-/, 'mysite-'));
I want to use this fiddle to work with a variable instead of text, this is the line:
addFormatter(input, regexPrefix(/mysite-/, 'mysite-'));
As you can see it only allows you to input text after mysite-
which is how I want it to work. But I want to be able to use a variable where it says mysite-
. Like this:
addFormatter(input, regexPrefix(/$sitetitle/, $sitetitle));
Do you have any idea on how to do this?