I’m looking to create a text input that formats the inputted value as the user inputs it. As the formatting function strips additional characters from the string the input value doesn’t update. A bit of a contrived example, repl link
<script>
let value = "[hello]"
const parse = (value) => value.replace(/[\[\]&]+/g, '');
let parsed = parse('[hello]');
const onChange = (event) => {
parsed = parse(event.target.value);
};
</script>
<h1>{parsed}</h1>
<input type="text" value={parsed} on:input={onChange} />
The onChange function strips the square brackets from the string but the value in the input doesn’t update if I type brackets into the input, I assume since they are stripped the value of parsed remains the same so doesn’t trigger an update. I thought about putting it inside a key block but then I’d have to track the position of the cursor, is there another solution?
>Solution :
Try this instead, and look up two way data binding in Svelte.
<script>
let value = "[hello]"
// strips any square brackets from string
const parse = (value) => value.replace(/[\[\]&]+/g, '');
let parsed = parse('[hello]');
const onChange = () => {
parsed = parse(parsed);
};
</script>
<h1>{parsed}</h1>
<input type="text" bind:value={parsed} on:input={onChange} />