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, "<").replace(/>/g, ">");
$('#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);
}
}
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;
}
in your context change this replace(/\\n/g, "<br />");
to this replace(/\\\\n/ig,'<br/>');
// i flag stands for case insensitve
here is a simple demo :
$(document).ready(function(){ var template = $.trim($('#toReplace').html()); //console.log(template); var replaced = template.replace(/\\\\n/ig,'<br/>'); console.log(replaced); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script> <div id="toReplace"> <span>hello world \\n</span> <span>hello world \\n</span> <span>hello world \\n</span> <span>hello world \\n</span> </div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.