0

From what I have seen so far here on stackoverflow, there are some recommendations about the String.replaceAll() function, or using javascript with the input ID. The code below will introduce a space after five characters, but I need it to add the space after the slash character is typed.

For example: if the user is typing abc12c/edfte; I need it to introduce a space after the slash character is typed to obtain this result: abc12c/ edfte.

    document.getElementById('target').addEventListener('input', function (e) {
    var target = e.target, position = target.selectionEnd, length = target.value.length;
  
    target.value = target.value.replace(/\s/g, '').replace(/(\d{5})/g, '$1 ').trim();
    target.selectionEnd = position += ((target.value.charAt(position - 1) === ' ' && target.value.charAt(length - 1) === ' ' && length !== target.value.length) ? 1 : 0);
});

<label id="target" contenteditable="true" type="text"/>someText</label>

I appreciate any guidance.

Fquintero
  • 45
  • 9
  • Can you you show an example how it should look like? – Tushar Gupta Mar 09 '22 at 22:15
  • Hi Tushar. Absolutely! Usually, the user types something like this: abcdef/ghijk. I need to separate it and look like this: abcdef/ ghijk. Insert a space the moment the user types the slash character. – Fquintero Mar 09 '22 at 22:17

1 Answers1

0

You may use replace to add a space after a /. Also, you should keep track of the caret position in the contenteditable element so the user can continue typing without loosing the position where they was typing.

Here's a live demo:

const target = document.getElementById('target'),
  regExp = /\/([\S])/;

target.addEventListener('input', () => {
  const selectionObj = window.getSelection(),
    currentCaretPosition = selectionObj.anchorOffset;
  if (regExp.test(target.textContent)) {
    const range = document.createRange();
    /** add a space after "/" */
    target.textContent = target.textContent.replace(regExp, '/ $1');
    /** fix the caret position */
    range.setStart(target.childNodes[0], currentCaretPosition + 1 > target.textContent.length ? target.textContent.length - 1 : currentCaretPosition + 1);
    range.collapse(!0);
    selectionObj.removeAllRanges();
    selectionObj.addRange(range);
  }
});
<label id="target" contenteditable="true" type="text" />someText</label>

The code portion that deals with setting the caret position is highly influenced by @tim-down's answer and I just made some tweaks to be compatible with the current situation.

ThS
  • 4,597
  • 2
  • 15
  • 27