Best
Best

Reputation: 2318

Get rid or hide html tags from textarea in Javascript

I retrieved a body of a textarea using json but the text appears to come with html tags due to some styles have been previously set.

How would I be able to display these lines of text on a new textarea without these html tags being visible? I don't want to get rid of them completely because I still want to keep the styles for the future use.

Upvotes: 0

Views: 6178

Answers (2)

Waruna Manjula
Waruna Manjula

Reputation: 3487

textarea{width:100%;min-height:75px}
<textarea id="input">
    <p>This is html</p>
    <p>This is html</p>
    <p>This is html</p>
</textarea>

<button onClick="removeTags()">Remove</button>

<textarea id="output"></textarea>

<script>
function removeTags(){
  var input = document.getElementById('input');
  var output = document.getElementById('output');
  output.value = input.value.replace(/(<([^>]+)>)/ig,"");
}
removeTags();
</script>

Upvotes: 1

Mohsen
Mohsen

Reputation: 65785

You need to escape html tags from your incoming string from textarea. By a regular expression like /<(.|\n)*?>/ you can find opening html tags and with /<(\/.|\n)*?>/ you can find closing tags.

Here is my example:

HTML

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />

</head>
<body>
  <textarea id="input">
    <p>This is html</p>
  </textarea>
  <textarea id="output">

  </textarea>

JavaScript

var input = document.getElementById('input'),
    output = document.getElementById('output');
output.value = input.value.replace(/<(.|\n)*?>/, '').replace(/<\/(.|\n)*?>/, '');

Live in: JSBin

You may want to detect closing tags like /> with this regular expression: /\/(.|\n)*?>/

Upvotes: 2

Related Questions