Home > Software design >  How to replace string in a line where caret is using JavaScript?
How to replace string in a line where caret is using JavaScript?

Time:09-03

I'm trying to figure out how I will target a line where the caret is currently in, and then do some basic replace in that line.

Here's the sample I have:

function process() {
  //Onclick of this button, remove "aaa" and "bbb" wherever it appears only where the caret is currently in
  let textarea = document.getElementById("textarea1");
  textarea.value = textarea.value
    .replaceAll('aaa', "")
    .replaceAll('bbb', "")
}
<textarea id='textarea1'>
aaaline1bbb
aaaline2bbb
line3
</textarea>
<button onclick='process();'>Process</button>

Here, whenever a user places their caret in line 1 or line 2, it will delete both "aaa" and "bbb" in the whole line. This is just a sample for what I really want to do.

The main problem I have is how to target a line where the caret is.

Thank you in advance for any help!

CodePudding user response:

You can use the answer linked in the comment to figure out where the cursor is, and then split the input by line and use your replacement only on the current line.

If I understand your requirement properly, here's a working sample.

function lineCursorIsOn(textarea) {
  return textarea.value.substring(0, textarea.selectionStart).split("\n").length;
}

function process() {
  //Onclick of this button, remove "aaa" and "bbb" wherever it appears only where the caret is currently in
  let textarea = document.getElementById("textarea1");
  const cursorLineNumber = lineCursorIsOn(textarea);
  textarea.value = textarea.value.split("\n").map(function(line,index) {
    const currentLineNumber = index 1;
    if (currentLineNumber == cursorLineNumber) return line.replaceAll("aaa", "").replaceAll("bbb", "");
    return line;
  }).join("\n");
}
<textarea id='textarea1'>
aaaline1bbb
aaaline2bbb
line3
</textarea>
<button onclick='process();'>Process</button>

CodePudding user response:

textarea.selectionStart will get you the caret. The rest of this is looping through the lines to find the one which contains the starting character, and applying the replace on that line only

function process() {
  let textarea = document.getElementById("textarea1");
  console.log(textarea.selectionStart);
  let selectionStart = textarea.selectionStart
 
  const lines = textarea.value.split(/\n/g)
  for(let i = 0; i < lines.length; i  ){
    selectionStart -= lines[i].length;
    if(selectionStart < 0){
        lines[i] = lines[i].replaceAll(/[aaa|bbb]/g, '');
        textarea.value = lines.join('\n');
      break;
    }
  }
}
<textarea id='textarea1' contenteditable="true">
aaaline1bbb 
aaaline2bbb 
line3
</textarea>
<button onclick='process();'>Process</button>

  • Related