Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to restrict number of characters per line in textarea?

I have one Ext JS TextArea. There I want to restrict my characters to 15 characters in each line and total number of lines should be not more than 10.

What I am tring to do here is

function(){
    var myValue = this.getValue();
    var myValueData = myValue.split(/\r*\n/);
    myValueData.length = 10;    
}

Ideally it should ommit all the lines after line number 10, but is not happening. Also how to restrict only upto 15 characters per line?

like image 302
David Avatar asked Jul 24 '18 06:07

David


People also ask

How do I limit characters in a textarea?

The HTML <Textarea>maxlength attribute is used to specify the maximum number of characters enters into the Textarea element. Attribute Value: number: It contains single value number which allows the maximum number of character in Textarea element.

How can you set a character limit to a field?

To set the maximum character limit in input field, we use <input> maxlength attribute. This attribute is used to specify the maximum number of characters enters into the <input> element. To set the minimum character limit in input field, we use <input> minlength attribute.

Does Maxlength work on textarea?

The maxlength attribute defines the maximum number of characters (as UTF-16 code units) the user can enter into an <input> or <textarea> .


1 Answers

This problem is prefect for regex...

My solution focuses on the "max char width" and "max line number" requirements which I don't consider to be the same as "max char count" due to wrapping on words. Because this solution uses plain regex it works best with plain-text with newline chars \n for line breaks rather than html.

This function is idempotent which means it's output can be piped into it's input without issue. It's also very efficient because it's pure regex. Both of these attributes make it perfect for dropping into an onchange handler to update text on every key-press without incurring large performance penalties.

const fit = (str, w = 80, h = 24) => {
    w = new RegExp(`(?![^\\n]{1,${w}}$)([^\\n]{1,${w}})\\s`, 'g');
    str = str.replace(w, '$1\n');
    h = new RegExp(`(((^|\\n)[^\\n]*){${h}})((($|\\n)[^\\n]*)+)`);
    str = str.replace(h, '$1');
    return str;
};

This function will format the string into the given width / height, but it does so in a very agreeable way: The wrapping regex is considerate of existing new lines which is why it's idempotent, and breaks lines between words not through them. For an in depth explanation of how the word wrap regex works and why it's robust, see my answer for word wrapping strings in JavaScript with regex:

Wrap Text In JavaScript

like image 179
Thomas Brierley Avatar answered Sep 17 '22 19:09

Thomas Brierley