首页 > 解决方案 > 如何将每个空格都算作一个字符?

问题描述

使用 CK-Editor,我允许用户在其中粘贴字符。我没有将 HTML 标签算作一个字符(我只是忽略了 HTML 标签),如果用户输入一个空格,我会将其算作一个字符。最后,我 允许用户输入最多 50 个字符。

我的问题:

1)如果用户粘贴 50 个字符(包括空格),CK-editor 应该将每个空格都算作一个字符。

2)如果用户输入超过50 个字符,则显示一条警告消息(“您不能输入超过 50 个字符”),并且只显示 50 个字符。我试过做:
event.data.dataValue = str.substr(0 , textLimit);但它总是摆脱空格并把multiple spaces它当作一个single space.

3)如果用户粘贴 9 个字符 6 次。示例:用户粘贴 9 个字符,然后再粘贴 9 个字符,再粘贴 9 个字符,再粘贴 9 个字符,再粘贴 9 个字符,然后再粘贴 9 个字符。一旦超过 50 个字符,用户应该收到一条警告消息(“您不能输入超过 50 个字符” ),但仍然显示 50 个字符。有没有更好的方法来防止用户粘贴超过 50 个字符?提前非常感谢!

这是我的代码:现场演示:现场演示

CKEDITOR.instances.foo.on('paste',function(event){
 var textLimit = 50;
 var str = event.data.dataValue.replace(/<[^>]+>/g, '').replace(/&nbsp;/g, ' ');

 if (str.length >= textLimit) {
 event.data.dataValue = str.substr(0 , textLimit);
 } 
}); 

注意: - 我正在使用这个网站来计算字符 - https://www.lettercount.com/

在此处输入图像描述

标签: javascriptckeditor

解决方案


试试 wordcount 插件。https://ckeditor.com/cke4/addon/wordcount 在 ckeditor 文件夹中的 config.js 上,使用它来配置 wordcount。

config.wordcount = {

        // Whether or not you want to show the Paragraphs Count
        showParagraphs: false,

        // Whether or not you want to show the Word Count
        showWordCount: false,

        // Whether or not you want to show the Char Count
        showCharCount: true,

        // Whether or not you want to count Spaces as Chars
        countSpacesAsChars: true,

        // Whether or not to include Html chars in the Char Count
        countHTML: false,

        // Maximum allowed Word Count, -1 is default for unlimited
        maxWordCount: -1,

        // Maximum allowed Char Count, -1 is default for unlimited
        maxCharCount: 100,

        // Add filter to add or remove element before counting (see CKEDITOR.htmlParser.filter), Default value : null (no filter)
        filter: new CKEDITOR.htmlParser.filter({
            elements: {
                div: function (element) {
                    if (element.attributes.class == 'mediaembed') {
                        return false;
                    }
                }
            }
        })
    };


推荐阅读