user2587454
user2587454

Reputation: 913

remove html tags from string js/jquery

I'm trying to show a text that i'm getting from the server with html tags.

Let's say i got

"a\nb\nc\nd\ne\nf\n"

and i want to show

a
b
c
d
e
f

i tried using jquery text() but i get empty string:

var answer = params.question.answer;
$('#answer_text').html($(answer).text());

i also tried with regex but nothing happens:

var regex = /(<([^>]+)>)/ig;
var answer = params.question.answer.replace(regex, '');
$('#answer_text').html(answer);

Upvotes: 0

Views: 112

Answers (3)

Arun P Johny
Arun P Johny

Reputation: 388436

Another option is to use the white-space rule

var answer = "a\nb\nc\nd\ne\nf\n";
$('#answer_text').html(answer);
#answer_text {
  white-space: pre-line;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="answer_text"></div>

Upvotes: 0

Prasanna
Prasanna

Reputation: 779

Using REGEX Remove \n and add <br /> tag.

Try:

var answer = "a\nb\nc\nd\ne\nf\n";
var regex = /\n/gi;
$('#answer_text').html(answer.replace(regex, "<br />"));

Demo

Upvotes: 2

Milind Anantwar
Milind Anantwar

Reputation: 82241

You need to convert \n into <br/> for creating line breaks in html:

var answer= "a\nb\nc\nd\ne\nf\n";
$('#answer_text').html(answer.replace(/\n/g, "<br />"));

Working Demo

Upvotes: 2

Related Questions