javascript - 验证一个长字符串是否有足够的可破坏空间用于显示
问题描述
我在打印表格内容时遇到问题,其中用户输入了没有空格的垃圾字符串,因此我无法以一致的方式对表格单元格内容进行自动换行...因此我想在输入进入打印阶段之前对其进行验证,避免打印引擎不支持或不完全支持的 CSS。
我想限制连续字符,所以我想出了这个解决方案,但不确定它是否真的是解决这个问题的最佳方法......
const limit = 25; // an abitrary number
/* a large chunk of text maybe containing
spaces to be aligned with data in a table */
let str = some_user_input;
/* split the string to array values using
any whitespace (added 'g' just for safety sake) */
if(str.length){
let spaced = str.split(/\s+/g);
//check we have array
if(spaced.length){
//check array items for exceeding contiguous character limit
for(let i = 0; i < spaced.length; i++){
if(spaced[i].length > limit){
return false;
}
}//endLoop
}
else{
if(str.length > limit) return false;
}
}
return true;
解决方案
由于您使用的是正则表达式,我可能只使用一个来检查字符串中是否存在没有空格的连续字符。就像是:
const limit = 4;
const reLimit = new RegExp(`\\S{${limit},}`);
const validate = (str) => !reLimit.test(str);
console.log(validate("foo bar")) // true
console.log(validate("foo barz")) // false
推荐阅读
- javascript - 如何将对象转换为嵌套数组?
- java - 我无法将自定义 jar 文件导入 NetBeans 项目
- sass - 在项目中使用 sass 时如何修改 antd 主题变量?
- javascript - 如何在chartjs画布中绑定touchmove?
- python - 图像数据增强
- node.js - 我想用 express 连接到 sql server 是 sql server 还是我的代码的问题?
- selenium-webdriver - 在范围报告中,5 个屏幕截图在其他系统中被破坏,在我的本地系统中工作正常
- for-loop - 为目录中的每个波段栅格创建栅格堆栈
- javascript - 使用异步函数在 NodeJS 中下载文件时遇到问题(使用管道)
- java - 从应用程序更改 Android 中的系统 EQ 设置