-2

I am trying to write a JS function that takes a block of text pasted inside textarea, removes line breaks but keeps paragraph breaks, and updates the text inside that textarea before I submit a form.

I have attempted to do it this way:

<textarea name="sum" id="sum" onpaste="frmt()"></textarea>

JS:

function frmt() {
    const tar = document.getElementById("sum");
    const reg = /[\r\n](?![\r\n])/g;        
    const str = tar.value;  
    tar.innerHTML = str.replace(reg, "");
}

What am I missing?

santa
  • 12,234
  • 49
  • 155
  • 255
  • 1
    Where is the `frmt` function? What is the problem? Inline event handlers like `onpaste` are [not recommended](/q/11737873/4642212). They are an [obsolete, hard-to-maintain and unintuitive](/a/43459991/4642212) way of registering events. Always [use `addEventListener`](//developer.mozilla.org/docs/Learn/JavaScript/Building_blocks/Events#inline_event_handlers_%E2%80%94_dont_use_these) instead. – Sebastian Simon Jan 12 '22 at 00:27
  • 1
    ` – Phil Jan 12 '22 at 00:31

2 Answers2

1
<textarea name="sum" id="sum"></textarea>

<script>
  const sum = document.getElementById('sum');

  sum.addEventListener('paste', () =>
    setTimeout(
      () => (sum.value = sum.value.replace(/[\r\n](?![\r\n])/g, '')),
      0
    )
  );
</script>

https://developer.mozilla.org/en-US/docs/Web/API/Element/paste_event

amlxv
  • 1,610
  • 1
  • 11
  • 18
1

<textarea> is not supported .innerHTML so you need to set values through .value and you can use oninput event.

This event occurs when the value of an <input> or <textarea> element is changed.

Helpful links:
https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/oninput https://www.w3schools.com/jsref/event_oninput.asp

function frmt(id){    
    const tar = document.getElementById(id);
    const reg = /[\r\n](?![\r\n])/g;
    const str = tar.value;
    tar.value = str.replace(reg, "")
}
textarea{
  width: 95%;
  height: 160px;
}
<textarea name="sum" id="sum" oninput="frmt('sum')"></textarea>
Raeesh Alam
  • 3,380
  • 1
  • 10
  • 9