How to limit the words input in quill.js?

Member

by kadin , in category: Javascript , 5 months ago

How to limit the words input in quill.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by brandy , 4 months ago

@kadin 

Quill.js does not have a built-in feature to limit the number of words inputted by the user. However, you can achieve this by adding a custom handler to check the number of words being inputted and restrict further input once the limit is reached.


Here is an example code snippet that demonstrates how to limit the number of words in a Quill editor:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
var quill = new Quill('#editor', {
  theme: 'snow',
  modules: {
    toolbar: [
      [{ 'header': [1, 2, false] }],
      ['bold', 'italic', 'underline']
    ]
  }
});

var maxLength = 10; // Maximum number of words allowed

quill.on('text-change', function() {
  var text = quill.getText();
  var words = text.trim().split(/s+/).length;
  
  if (words > maxLength) {
    // Delete the excess text
    quill.deleteText(quill.getLength() - (text.length - maxLength), text.length - maxLength);
  }
});


In this code snippet, we create a new Quill editor instance and specify the maximum number of words allowed (in this case, 10). We then listen for the 'text-change' event, which is fired whenever the user types or deletes text in the editor. Inside the event handler, we check the number of words in the editor's content and delete any excess text if the limit is exceeded.


You can customize this code further to add an alert message or disable input once the word limit is reached.