问题描述
让我说我有这个字符串,其中包含非空格字符:
thisHُ is a long string I cant display
如您所见,这个“ H ُ”现在包含非空格字符,我想将字符串短,所以我这样做了:
var text = "thisHُ is a long string I cant display"
text =text.replace(/^((.){0,9})(.*)/gm,"$1");
console.log(text);
这将给出:
thisHُ is
但是我不想计算非空格字符,我想通过忽略“计数”非空格字符来缩短字符串,我也想在不削减单词边界的情况下缩短字符串。
解决方法
您可以使用
-
s.match(/^(?:\s*\S){1,9}\S*/)[0]
-
s.match(/\S*(?:\S\s*){1,9}$/)[0]
请参见regex demo #1和regex demo #2。
^(?:\s*\S){1,9}\S*
正则表达式匹配1到9个出现的0+空格,后跟字符串开头的单个非空格字符,然后匹配任何0+非空格字符。
\S*(?:\S\s*){1,9}$
正则表达式将匹配0+个非空格字符,然后匹配一个到九个出现的单个非空格字符,然后在字符串末尾匹配0+个空格。
JavaScript演示
const text = "thisHُ is a long string I cant display";
const startMatch = text.match(/^(?:\s*\S){1,9}\S*/);
const endMatch = text.match(/\S*(?:\S\s*){1,9}$/);
if (startMatch) console.log(`Match at start: ${startMatch[0]}`);
if (endMatch) console.log(`Match at end: ${endMatch[0]}`);