2017-04-23 146 views
0

当用户写入某些内容时,有时他们会在一行中留下两个或多个空格,有没有办法通过jQuery来防止这种情况?JQuery在用户输入contenteditable时删除多个输入

例如:

我不想让用户打字这样的:

Hi Dear, 






This is some text. 



Second text 




Thirt text and ..... 

所以我们要删除多个空格行是这样的:

Hi Dear, 

This is some text. 

Second text. 

Thirt text and.... 

我想我们可以用jquery keyup函数用正则表达式来实现,就像

$(document).ready(function() { 
    $("body").on("keyup", ".text", function() { 
     var text = $(".text"); 
     text = text.replace(/(\r\n|\r|\n){2}/g, '$1').replace(/(\r\n|\r|\n){3,}/g, '$1\n'); 
    }); 
}); 

有没有办法做到这一点?我可以用php正则表达式来做到这一点。但有没有办法做到这一点时,用户写的文本,而不需要PHP?

我想说,写文本时可以不允许多余的空格。

<div class="text" contenteditable="true" placeholder="User can write text here More than three sub-spaces will not be allowed. "></div> 
+0

您提供的代码片段正常工作。 $(“。text”)。html(text)'''你可能需要在删除多个输入后将文本插回contenteditable。你面临的问题是什么? – Santosh

+0

我已经更新了DEMO。这里是链接https://codepen.io/anon/pen/KmMbGq。 – Santosh

回答

0

就做这样的事情:

var lastKey = ''; 
$("#id").keypress(function(e){ 
    if(e.which == 13 && lastKey == 13) 
     e.preventDefault() 
    lastKey = e.which; 
}); 

它检查2个连续输入按键,而忽略第二之一。它比使用正则表达式更快,更清洁。

0

使用jQuery texttextarea不工作,你会觉得它永远的工作方式,使用jQuery val和使用事件blur它激发当用户离开textarea你也可以使用change如果你想 一次这里是工作代码,

$('.text').on('blur' , function(){ 
     $(this).val($(this).val().replace(/\n\n+/g , "\n")) 
})