You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

textarea中jQuery处理\r\n换行正则失效,求解决方案

解决方案

核心问题修正

你的代码失效主要有两个关键原因:

  • 错误使用.html()设置textarea内容:textarea的显示内容由value属性控制,.html()修改的是元素内部HTML,不会反映到输入框的可见内容中,必须用.val()。
  • 错误的换行符处理:\\n会显示为字面量\n而非换行;
是HTML实体,但textarea不识别实体,只支持原生换行符\n(现代浏览器兼容)。

正确实现代码

场景1:从接口获取数据后填充并格式化

// 假设已获取后端返回的data对象
const neResponse = data.ne_response;

// 1. 统一换行符,合并多余空行
const normalizedText = neResponse
  .replace(/\r\n|\r|\n/g, '\n') // 将所有换行格式统一为\n
  .replace(/\n{2,}/g, '\n\n'); // 保留最多连续两个换行,避免过多空行

// 2. 缩进美化:命令提示符行不缩进,内容行缩进2空格
const formattedText = normalizedText.split('\n').map(line => {
  if (/Router@\w+>/.test(line) || line.trim() === '') {
    return line;
  }
  return '  ' + line;
}).join('\n');

// 3. 将处理后的内容设置到textarea
$('#viewConfig').val(formattedText);

场景2:监听用户输入/粘贴,自动格式化

$('#viewConfig').on('input', function() {
  let content = $(this).val();
  
  // 统一换行并合并空行
  const normalizedContent = content.replace(/\r\n|\r|\n/g, '\n').replace(/\n{2,}/g, '\n\n');
  
  // 添加缩进美化
  const indentedContent = normalizedContent.split('\n').map(line => {
    if (/Router@\w+>/.test(line) || line.trim() === '') {
      return line;
    }
    return '  ' + line;
  }).join('\n');
  
  // 避免无限循环:仅当内容变化时才重新赋值
  if (indentedContent !== $(this).val()) {
    $(this).val(indentedContent);
  }
});

完整示例代码

<textarea class="form-control" id="viewConfig" rows="10"></textarea>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
// 模拟后端返回数据
const mockData = {
  "status": "success",
  "output": {
    "ipv4_address": "xxx/xx",
  },
  "ne_response": "... \r\r\n--- {master}\r\nRouter@xyz> show ... inet address xxx/30\r\n\r\n{master}\r\nRouter@xyz> "
};

$(document).ready(function() {
  // 初始化填充格式化后的内容
  const neResponse = mockData.ne_response;
  let formattedText = neResponse.replace(/\r\n|\r|\n/g, '\n').replace(/\n{2,}/g, '\n\n');
  
  formattedText = formattedText.split('\n').map(line => {
    if (/Router@\w+>/.test(line) || line.trim() === '') {
      return line;
    }
    return '  ' + line;
  }).join('\n');
  
  $('#viewConfig').val(formattedText);
  
  // 监听用户输入自动格式化
  $('#viewConfig').on('input', function() {
    let content = $(this).val();
    const normalizedContent = content.replace(/\r\n|\r|\n/g, '\n').replace(/\n{2,}/g, '\n\n');
    
    const indentedContent = normalizedContent.split('\n').map(line => {
      if (/Router@\w+>/.test(line) || line.trim() === '') {
        return line;
      }
      return '  ' + line;
    }).join('\n');
    
    if (indentedContent !== $(this).val()) {
      $(this).val(indentedContent);
    }
  });
});
</script>

内容的提问来源于stack exchange,提问作者mastersuse

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 15:17:48