首页 > 解决方案 > 验证一个长字符串是否有足够的可破坏空间用于显示

问题描述

我在打印表格内容时遇到问题,其中用户输入了没有空格的垃圾字符串,因此我无法以一致的方式对表格单元格内容进行自动换行...因此我想在输入进入打印阶段之前对其进行验证,避免打印引擎不支持或不完全支持的 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;

标签: javascriptarraysstringvalidation

解决方案


由于您使用的是正则表达式,我可能只使用一个来检查字符串中是否存在没有空格的连续字符。就像是:

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

推荐阅读