How to get value of escape sequences inside HTML textarea

57 views Asked by At

I have a textarea, and inside of it, I would like to be able to input text alongside escape sequences.

For example, lets say that inside the textarea is:

Hello\nWorld.

Now, If I wanted to print that value to the console by using:

console.log( document.getElementById('myTextArea').value )

The output that I would like would be:

Hello
World

But instead, it outputs:

Hello\nWorld

This makes since, because that's what I put in. But I would like to convert these sequences to their actual values

Now I'm sure this is possible with a simple string replace, like:

str.replaceAll('\\n', '\n')

But I would like to be able to do this with ANY escape sequence. like: \u0000, \r, \u0020

So is it possible to extract these sequences from a textarea?

1

There are 1 answers

0
Carsten Massmann On

Like @James already mentioned in his comment, the answer to this question can be found here: How do I decode a string with escaped unicode?

So, the following snippet should not be seen as an answer, but rather as a demo of how to apply the method described there on two textarea fields.

const [src,trg]=[...document.querySelectorAll("textarea")];
function parseText(){
 trg.value=(s=>{
  try{return decodeURIComponent(JSON.parse(`"${s}"`));}
  catch{return s;}
 })(src.value);
}
src.addEventListener("input",parseText);
parseText();
<textarea>Oh,%20hello\nworld \u2728\t\u263a</textarea><br>
<textarea></textarea>