javascript - 仅在每个前置标记之前和之后的所有新行上将\n 替换为 <br/>

标签 javascript jquery codeigniter

我正在使用 ajax 和 codeigniter 来提交我的问题的预览。

但我正在尝试替换 \n<br />仅在 pre 之前的所有新行上并在每个pre之后标签。

问题:如何确保它替换 \n仅在每个前置标记之前和之后的行上使用 `br?

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

最佳答案

我不知道是否有一种简单的方法可以在不解析的情况下做到这一点。假设您不想解析,我认为最简单的解决方案是将 CSS 规则应用于输入问题,就像它是 PRE 元素一样。

#preview{
    white-space: pre;
}

关于javascript - 仅在每个前置标记之前和之后的所有新行上将\n 替换为 <br/>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40315979/

相关文章:

javascript - 如何在 $compile 之后隐藏一个元素?

c# - 使用点(.) 将参数传递给 javascript 函数

javascript - 返回历史记录时的 Sammy.js 缓存和滚动位置

php - CodeIgniter:如何显示单个验证错误?

php - Codeigniter HMVC Ajax

javascript - jQuery 获取不是获取元素的 html

javascript - 标记它提交ID而不是值或标签

javascript - jQuery "this"的第一个 child

javascript - 使用js或jquery连接服务器

mysql - 使用 mysql join 显示不匹配值