输入文本后按两次回车触发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
相关产品推荐
相关产品推荐

