-1

// 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?

Barmar
  • 741,623
  • 53
  • 500
  • 612
joq3
  • 145
  • 7

1 Answers1

0

You can create a regexp dynamically using the RegExp() constructor.

addFormatter(input, regexPrefix(new RegExp('^' + $sitetitle), $sitetitle));
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • I just realised I missed this detail: `addFormatter(input, regexPrefix(/^mysite-/, 'mysite-'));`. This `^` disabled the possibility to put any letters before the word `mysite` Is it possible to integrate this too? – joq3 Oct 25 '18 at 18:40
  • Just use string concatenation. I've updated the answer. – Barmar Oct 25 '18 at 19:03