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?
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.
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.
The maxlength attribute defines the maximum number of characters (as UTF-16 code units) the user can enter into an <input> or <textarea> .
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With