![](/img/trans.png)
[英]Replace all break lines present in <pre> tag with <br> tag in javascript
[英]replace \n with <br /> only on the all new lines before pre and after each pre tag
我正在將Ajax與codeigniter一起使用以提交我的問題的預覽。
但我想,以取代\\n
與<br />
只有之前的所有新生產線pre
和后的每一個pre
標記。
問題:如何確保僅在每個pre標記之前和之后的行中用\\n
br替換\\n
?
<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>
控制者
<?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;
}
在您的上下文中更改此replace(/\\n/g, "<br />");
replace(/\\\\n/ig,'<br/>');
// i flag stands for case insensitve
這是一個簡單的演示:
$(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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.