I want to select a word or more words of the input and click push button to replace the selected portion of the string with an underscore.
This is not complete code but gives you the idea somehow:
const blankInput = document.getElementById('blank-input');
const dictatePush = document.querySelector('.dictate-push');
dictatePush.addEventListener('click', (e) => {
const start = blankInput.selectionStart;
const finish = blankInput.selectionEnd + 1;
blankInput.value = blankInput.value.substring(0, start) + '_';
});
input {
width: 50vw;
}
<input data-collect="blank" id="blank-input" type="text" value="Select (highlight) a word and click Push">
<button type="button" class="dictate-push">Push</button>
So if you type I think I might need a car and select the might as a word after clicking push we should get this:
I think I _ need a car
- Note that we want it clean so if you select the exact word or select
the word and surrounding spaces we should still get the same result. - we want to return the replaced word too, here it’s
might
How would you do this ?
>Solution :
You can include trimming of start and end of the original string, something like this:
const blankInput = document.getElementById('blank-input');
const dictatePush = document.querySelector('.dictate-push');
dictatePush.addEventListener('click', (e) => {
const value = blankInput.value;
const start = blankInput.selectionStart;
const finish = blankInput.selectionEnd;
if(start !== finish) { //There is a selection
const removedWord = value.substring(start, finish).trim();
const substringStart = value.substring(0, start).trimEnd();
const substringEnd = value.substring(finish).trimStart();
console.log("Result:", substringStart + " _ " + substringEnd);
console.log("Removed Word:", removedWord);
}
});
<input data-collect="blank" id="blank-input" type="text">
<button type="button" class="dictate-push">Push</button>