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

输入文本后按两次回车触发keyup事件时输出多一行换行的问题

问题:去除富文本输入中的多余换行符

我用以下代码实现React Native WebView内的富文本输入交互:

document.addEventListener("DOMContentLoaded", function() {
      $("#placeholder").on("click", function(){
           $("#contentHtml").focus();
           $(this).hide();
      })        
                            
      $("#contentHtml").on("keyup", function(e){
           var contentValue = e.target.innerText;
           window.ReactNativeWebView.postMessage(contentValue);
           if($(this).html().length === 0){
                $("#placeholder").show();
           } else {
                $("#placeholder").hide();
           }
      });
});

输入输出情况

  • 正常单行回车输入:
    输入内容:
this is line 1 <- 按回车后输入"this is line 2"

输出符合预期:

this is line 1
this is line 2
  • 多次回车后输入:
    在"this is line 2"后按两次回车,再输入"this is line 3",输出出现多余空行:
this is line 1
this is line 2


this is line 3

期望输出:

this is line 1
this is line 2

this is line 3

解决方案

通过正则表达式对获取到的文本内容做处理,将3个及以上连续的换行符替换为2个换行符,即可保留单个空行并去除多余换行。修改后的代码如下:

document.addEventListener("DOMContentLoaded", function() {
      $("#placeholder").on("click", function(){
           $("#contentHtml").focus();
           $(this).hide();
      })        
                            
      $("#contentHtml").on("keyup", function(e){
           // 压缩连续多换行,最多保留一个空行
           var contentValue = e.target.innerText.replace(/\n{3,}/g, '\n\n');
           window.ReactNativeWebView.postMessage(contentValue);
           if($(this).html().length === 0){
                $("#placeholder").show();
           } else {
                $("#placeholder").hide();
           }
      });
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 03:00:58