Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I replace the selected portion of an input value?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 ?

>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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading