javascript - 如何将每个空格都算作一个字符?
问题描述
使用 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(/ /g, ' ');
if (str.length >= textLimit) {
event.data.dataValue = str.substr(0 , textLimit);
}
});
注意: - 我正在使用这个网站来计算字符 - https://www.lettercount.com/
- 这是一张显示我如何计算空格的图像:
解决方案
试试 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;
}
}
}
})
};
推荐阅读
- ruby - 如何测试方法是否被调用
- html - 页脚外的文字
- android - 无法解析 ':app@debug/compileClasspath' 的依赖关系:无法解析 com.daimajia.slider:library:1.1.5
- python - 带有可选参数的适当方法签名
- vuejs2 - 在Vuejs中从json结果制作多维数组
- javascript - 在浏览器扩展中使用 libsodium.js
- elixir - 在开发中模拟 3rd 方库
- java - 如何优化以下程序?
- python - RuntimeError:当我加载 sklearn 模型时,字典在迭代期间更改了大小
- dart - flutter - 如何保持用户登录谷歌