wolfgang1983 wolfgang1983 - 1 month ago 12
Javascript Question

replace \n with <br /> only on the all new lines before pre and after each pre tag

I am using ajax with codeigniter to submit a preview of my question.

But I am trying to replace

\n
with
<br />
only on the all new lines before
pre
and after each
pre
tag.

Question: How can I make sure it replaces
\n
with `br only on the lines before and after each pre tag?

<script type="text/javascript">
$('#preview-question').on('click', function (e) {
$.ajax({
url: "<?php echo base_url('question/preview');?>",
type: 'POST',
data: {
title: $('#title').val(),
question: $('#question').val(),
'<?php echo $this->security->get_csrf_token_name(); ?>' : '<?php echo $this->security->get_csrf_hash(); ?>'
},
dataType: 'json',
success: function(response){
if (response.success) {
$('#preview').html(response.question.replace(/\n/g, "<br />").before('pre').after('pre'));
var htmlBRCleaned = $('#preview pre').html().replace(/<br\s?\/?>/, '').replace('<br\/>', '').replace(/</g, "&lt;").replace(/>/g, "&gt;");
$('#preview pre').html(htmlBRCleaned);
} else {

}
}

});

e.preventDefault();
});
</script>


Controller

<?php

class Question extends MY_Controller {

public $data = array();

public function __construct() {
parent::__construct();
}

public function index() {
}

public function create() {
$this->form_validation->set_rules('title', 'title', 'trim|required');
$this->form_validation->set_rules('question', 'question', 'trim|required|callback_question');

if ($this->form_validation->run() == true) {

}

$data['page'] = 'question/create';

$this->load->view($this->config->item('config_template') . '/template/template_view', $data);
}

public function question() {
if (empty($this->input->post('question'))) {
$this->form_validation->set_message('question', 'You have not asked a question');
return false;
} else {
return true;
}
}

public function preview() {

$data = array('success' => false, 'question' => '');

if ($_POST) {

$question = $this->input->post('question');

$data['question'] = $question;

$data['success'] = true;
}

echo json_encode($data);
}
}

Answer

I don't know if there is a easy way to do that without parsing. Supose you don't wanna parsing, the easiest solution I think is apply the CSS rule for entry question, like it was a PRE element.

#preview{
    white-space: pre;
}