I am trying to change the format of an input with a bind:value and a function, but when I change the format and in this case the length of the input changes compared to the original input the caret is placed between the characters and not at the end.
Also the input is a reusable component so I would prefer the fix to be done in the parent of this component, so as not to integrate additional logic into it.
If someone knows a solution I would appreciate it.
example: svelte playground
parent component:
<script> import InputComponent from "./InputComponent.svelte" let id = $state('') function formatId(value) { value = value.replace(/\D/g, ''); if (value.length < 2) return value; const idWithoutDash = value.slice(0, -1); const verifier = value.slice(-1); const formatted = idWithoutDash.replace(/\B(?=(\d{2})+(?!\d))/g, '.'); return `${formatted}-${verifier}`; }</script><InputComponent bind:value={() => id, (value) => id = formatId(value)}></InputComponent><p> {id}</p>
child component:
<script> let { value = $bindable() } = $props();</script><input bind:value={value} />
I was trying to format the user input as I was typing using bind:value and running a function, I expected the input to be smooth with the carot always at the end but the result is that the carot gets placed between the characters in the input if the input changes length.