Home > Software engineering >  How can I replace the selected portion of an input value?
How can I replace the selected portion of an input value?

Time:11-23

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" >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

  1. 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.
  2. we want to return the replaced word too, here it's might

How would you do this ?

CodePudding user response:

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" >Push</button>

CodePudding user response:

What i have done is taken the window selection, and replaced the selected bit with _ then pushed the value back into the input box.

Once all replacements are done i then search the string for double spaces and replace with a single to give expected results.

const blankInput = document.getElementById('blank-input');
const dictatePush = document.querySelector('.dictate-push');

dictatePush.addEventListener('click', (e) => {
  blankInput.value = blankInput.value.replace(window.getSelection().toString(), " _ ");
  blankInput.value = blankInput.value.replace("  ", " ");
});
input {
  width: 50vw;
}
<input data-collect="blank" id="blank-input" type="text" value="Select (highlight) a word and click Push">
<button type="button" >Push</button>

You can see a working codepen here:

https://codepen.io/SweetChillyPhilly/pen/YzvebPV

  • Related