当用户输入contenteditable

时间:2017-04-23 12:26:30

标签: javascript jquery

当用户写东西时,有时他们会连续留下两个或多个空格,有没有办法用jQuery来防止这种情况?

例如:

我不想让用户输入这样的内容:

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>

2 个答案:

答案 0 :(得分:0)

做到这样的事情:

    <a class="btn btn-large btn-blue" href="javascript:void(0);" 
    data-bind="click: $root.clickAction.bind($data, ActionType)">
    <span data-bind="text: Title">Register</span></a>

它检查2次连续输入键按下,并忽略第2次。它比使用正则表达式更快更干净。

答案 1 :(得分:0)

使用jquery text无法按照您认为的方式textarea工作,使用jquery val它始终有效并使用事件blur它会在用户触发一次离开textarea如果您愿意,也可以使用change 这是工作代码,

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