如何限制textarea中每行的字符数?

时间:2018-07-24 06:22:28

标签: javascript extjs

我有一个Ext JS TextArea。我想将每行中的字符限制为15个字符,总行数应不超过10个。

我想在这里做的是

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

理想情况下,它应该省略第10行之后的所有行,但不会发生。还有如何限制每行最多15个字符?

8 个答案:

答案 0 :(得分:4)

您可以尝试一下,虽然不完美,但应该可以。

使用更改侦听器,覆盖组件上的setValue或setRawValue函数可能更好。

https://fiddle.sencha.com/#view/editor&fiddle/2js1

   {
                xtype: 'textareafield',
                grow: true,
                name: 'message',
                fieldLabel: 'Message',
                anchor: '100%',
                listeners: {
                    change: function (cmp, newVal, oldVal) {
                        var arrayForEachLine = newVal.split(/\r\n|\r|\n/g);
                        var newVal = [];
                        Ext.Array.each(arrayForEachLine, function (line, index) {
                            if (line.length >= 10) {
                                offset = line;
                                while (offset.length > 0) {
                                    newVal.push(offset.substring(0, 10));
                                    offset = offset.substring(10);
                                }

                            } else {
                                newVal.push(line);
                            }
                            if (index === 10) return false;
                            if (newVal.length >= 10) {
                                newVal = newVal.slice(0, 10);
                                return false;
                            }
                        });
                        cmp.suspendEvent('change');
                        cmp.setValue(newVal.join('\n'));
                        cmp.resumeEvent('change');
                    }
                }
            }

答案 1 :(得分:3)

这可以通过使用更改侦听器来实现。我创建了一个demo (fiddle)。请看小提琴,因为那里的代码很整洁,也有注释。请在下面查看我的更改侦听器代码:

listeners: {
                change: function () { 
                    var myValue = Ext.getCmp('myField').getValue(); 
                    var lines = myValue.split("\n"); 
                    if (lines.length > 10) { 
                        alert("You've exceeded the 10 line limit!"); 
                        Ext.getCmp('myField').setValue(textAreaValue); 
                    } else { //if num of lines <= 10
                        for (var i = 0; i < lines.length; i++) { /
                            if (lines[i].length > 15) { /
                                alert("Length exceeded in line " + (i+1)); 
                                Ext.getCmp('myField').setValue(textAreaValue); 
                            } else if (lines[i].length <= 15 && i == lines.length - 1) { 
                                textAreaValue = myValue; 
                            }

                        }
                    }

                }
            }

如果此答案解决了您的问题,请将此答案标记为答案,因为这也将在以后帮助其他人。如果此答案有任何问题,请在评论中让我知道。如果我不是extjs专家,如果出现问题,很抱歉。但是我仍然尝试过。

答案 2 :(得分:2)

要限制textarea字符的长度,可以使用以下属性maxlength。

<textarea maxlength="50">

截断字符串或​​数字。

text_truncate = function(str, length, ending) {
if (length == null) {
  length = 100;
}
if (ending == null) {
  ending = '...';
}
if (str.length > length) {
  return str.substring(0, length - ending.length) + ending;
} else {
  return str;
}
};

您可以通过

调用它
text_truncate(yourContentToTruncate,15);

答案 3 :(得分:2)

这个问题对正则表达式来说是完美的...

我的解决方案着重于“最大字符宽度” “最大行数” 的要求,我认为这些要求与“ max字符数” 。由于此解决方案使用纯正则表达式,因此最适合与带有换行符\n的纯文本进行换行而不是html。

该函数是幂等的,这意味着它的输出可以毫无问题地通过管道传递到其输入中。它也是纯正则表达式,因此非常有效。这两个属性使其非常适合放入onchange处理程序中,以在每次按键时更新文本,而不会造成较大的性能损失。

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;
};

此函数会将字符串格式化为给定的宽度/高度,但这样做的方式非常符合[em] :包装式正则表达式考虑到了现有的新行,这就是为什么幂等并中断的原因单词之间的界线不是通过它们。有关自动换行正则表达式如何工作以及为何健壮的深入说明,请参阅我的关于使用正则表达式在JavaScript中自动换行字符串的答案:

Wrap Text In JavaScript

答案 4 :(得分:2)

此解决方案使用纯JavaScript。

基本思想是使用.match(/.{1,10}/g)创建由15个字符组成的大块数组,然后以换行符加入该数组 {{1} }再次创建一个字符串。仅使用join("\n")删除剩余的块即可限制行数。

我们正在使用splice(10, chunks.length - 1)事件,但这可能是另一个事件,这是因为在释放键之前不会触发代码。但是,如果我们将文本粘贴到文本区域内,则此代码也将起作用,因为也会触发该事件。

.onkeyup
document.getElementById("textArea").onkeyup = function() {

  var text = this.value.replace("\n", "");

  if (text.length > 15) {

    var chunks = text.match(/.{1,15}/g);

    if (chunks.length > 10) { 

      chunks.splice(10, chunks.length - 1);

      alert("if text have more than 10 lines is removed");
    }

    this.value = chunks.join("\n");

  }
};

答案 5 :(得分:1)

在指定textarea字段的位置,需要将'enforceMaxLength'属性设置为true,然后将'maxLength'属性设置为字符数作为限制。请为extjs找到以下示例代码。在示例中,我将限制设置为不超过10个字符。希望这会有所帮助。

Ext.create('Ext.form.Panel', {
title: 'Contact Info',
width: 300,
bodyPadding: 10,
renderTo: Ext.getBody(),
items: [{
    xtype: 'textarea',
    name: 'name',
    fieldLabel: 'Name',
    enforceMaxLength:true,
    maxLength:10,
    allowBlank: false  // requires a non-empty value
}]

});

答案 6 :(得分:0)

10行接受条件

$(document).ready(function(){

    var lines = 10;
    var linesUsed = $('#linesUsed');

    $('#countMe').keydown(function(e) {

        newLines = $(this).val().split("\n").length;
        linesUsed.text(newLines);

        if(e.keyCode == 13 && newLines >= lines) {
            linesUsed.css('color', 'red');
            return false;
        }
        else {
            linesUsed.css('color', '');
        }
    });
});

答案 7 :(得分:0)

我已经编写了将剪切的字符放在下一行开头的解决方案。只允许10行,每行15个字符。

Ext JS解决方案

不幸的是,SO上的代码片段不适用于Ext JS。

因此,您可以在this codepen.io link上看到它。

Ext.application(
{
    name: 'ExtApp',
    launch: function ()
    {
        Ext.create('Ext.form.Panel',
        {
            title: 'Sample TextArea',
            bodyPadding: 10,
            renderTo: Ext.getBody(),
            title: 'Restricted number of characters per line in textarea',
            height: 500,
            width: 700,
            items:
            [{
                xtype: 'textareafield',
                grow: true,
                fieldLabel: 'Please write your text:',
                height: 320,
                width: 480,
                listeners:
                {
                    change: function(self, newVal)
                    {
                        var chunks = newVal.split(/\r*\n/g),
                            lastLineCutedTxt = '';

                        for(var i = 0; i < chunks.length; i++)
                        {
                            chunks[i] = lastLineCutedTxt + chunks[i];

                            if(chunks[i].length > 15)
                            {
                                lastLineCutedTxt = chunks[i].slice(15);
                                chunks[i] = chunks[i].slice(0, 15);
                            }
                            else lastLineCutedTxt = '';
                        }

                        if(lastLineCutedTxt != '')
                            chunks.push(lastLineCutedTxt);

                        self.suspendEvent('change');
                        self.setValue(chunks.slice(0, 10).join('\n'));
                        self.resumeEvent('change');
                    }
                }
            }]
        });
    }
});
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/ext-all.js"></script>
<link rel="stylesheet" type="text/css" href="http://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-triton/resources/theme-triton-all.css">
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-triton/theme-triton.js"></script>

使用纯JavaScript的解决方案

var txtArea = document.getElementById('txt-area')
txtArea.onkeyup = function(e)
{
    var chunks = this.value.split(/\r*\n/g),
        lastLineCutedTxt = '';

    for(var i = 0; i < chunks.length; i++)
    {
        chunks[i] = lastLineCutedTxt + chunks[i];

        if(chunks[i].length > 15)
        {
            lastLineCutedTxt = chunks[i].slice(15);
            chunks[i] = chunks[i].slice(0, 15);
        }
        else lastLineCutedTxt = '';
    }

    if(lastLineCutedTxt != '')
        chunks.push(lastLineCutedTxt);

    this.value = chunks.slice(0, 10).join('\n');

};
<textarea id="txt-area" rows="16" cols="35"></textarea>