0

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);

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

7 Comments

That's what I thought.
something is really wierd. if i'll do exactly the same it will work but if i'll change var answer= "a\nb\nc\nd\ne\nf\n"; to var answer = params.question.answer it won't work. the value from params.question.answer is exactly as "a\nb\nc\nd\ne\nf\n"
what does ` params.question.answer` alerts??
it's a value i get from json and passing it to the function. the value inside is a string with "a\nb\nc\nd\ne\nf\n"
what about $('#answer_text').html(params.question.answer.replace(/\n/g, "<br />"));
|
2

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

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.