Home > front end >  How to convert textarea value to a string in JavaScript
How to convert textarea value to a string in JavaScript

Time:12-22

I want to convert the textarea input value to a string, but does not work and output is: [Object HTMLInputElement], I've used regex, it works properly when I hard code a string

let input = document.getElementById("input").toString();
  let result = input.replace(/(?<=(?:^|[.?!])\W*)[a-z]/g, i => i.toUpperCase());
  console.log(result);

CodePudding user response:

You should read the value of the <textarea> each time its content changes. The "input" event can be used for this.

let textarea = document.getElementById("textarea");
textarea.addEventListener("input", function(e){
  let result = textarea.value.replace(/(?<=(?:^|[.?!])\W*)[a-z]/g, i => i.toUpperCase());
  console.log(result);
});
<textarea id="textarea"></textarea>

CodePudding user response:

The value of textarea is already string, you just need to extract it the right way, which is using textarea.value

let input = document.getElementById("input");
let value = input.value;
console.log(value);
<textarea id="input">This textarea value</textarea>

  • Related