2017-04-23 103 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")) 
})