将句子串分成子串=<最长单词的长度

时间:2015-08-16 15:00:09

标签: javascript regex string typography photoshop-script

我是新手,并且有一堆数据字符串(句子)。我试图将每个句子分成子串,其中每个字符串的长度不超过该句子中最长单个单词的长度,并返回其原始序列中的所有单词,并带有换行符(Photoshop回车,“\ r”)除以那个句子的子串。每个字符串中的单词不是连字符(只有完整的单词或单词组在空格所在的位置*)。*编辑:使用最大字符,直到最长单词的字符数...所以一行将有2或者可能是3个单词,直到最长单词的长度。

我找到了分割和计算单词数组的例子,按字符长度排序,或者在设置字符,所有空格等处添加换行符。但是我所知道的任何内容都不足以看到对此结果的简单修改。非常感谢任何帮助。

2 个答案:

答案 0 :(得分:1)

使用替换,您可以用\n替换所有空格以获得结果。

a = 'This show navigation menu when you scroll up page 0px up (in right-way). But trying to show after 200px (on page scroll-up) means not showing right way want show and hide after 200px when scroll \n up page.'
b = a.replace(/\s{1,}/g,"\n");
alert(b)

答案 1 :(得分:0)

尝试将.split与正则表达式一起使用:

var a = 'This show navigation menu when you scroll up page 0px up (in right-way). But trying to show after 200px (on page scroll-up) means not showing right way want show and hide after 200px when scroll \n up page.'
var outputArray = a.split(/\s+/);
console.log(outputArray);

如果你想要更直接的方式:

var a = 'This show navigation menu when you scroll up page 0px up (in right-way). But trying to show after 200px (on page scroll-up) means not showing right way want show and hide after 200px when scroll \n up page.'

a.match(RegExp('.{0,' + Math.max.apply(0, a.match(/\w+/g).map(function(l) {
    return l.length;
})) + '}', 'g');

ES6:

a.match(RegExp(`.{0,${Math.max(...a.match(/\w+/g).map(l=>l.length))}}`), 'g')
相关问题