我正在尝试为以下测试找到解决方案: 你应该能够在给定数量的列中包裹行,而不会破坏单词
输入字符串是:
var inputStrings = [
'abcdef abcde abc def',
'abc abc abc',
'a b c def'
];
,输出应为:
var outputStrings = [
'abcdef\nabcde\nabc\ndef',
'abc\nabc\nabc',
'a b c\ndef'
];
我想出了这个jsfiddle,它通过了3个测试中的2个: https://jsfiddle.net/ticuclaudiu/yh269rc0/5/
function wordWrap(str, cols) {
var formatedString = '',
wordsArray = [];
wordsArray = str.split(' ');
for(var i = 0; i < wordsArray.length; i++) {
if(wordsArray.indexOf(wordsArray[i]) === 0) {
formatedString += wordsArray[i];
} else {
if(wordsArray[i].length > 1) {
formatedString += '/n' + wordsArray[i];
} else {
formatedString +=' ' + wordsArray[i];
}
}
}
console.log(formatedString);
}
//wordWrap('abcdef abcde abc def', 5);
wordWrap('abc abc abc', 5);
//wordWrap('a b c def', 5);
//'abcdef abcde abc def' | 'abcdef\nabcde\nabc\ndef',
//'abc abc abc' | 'abc\nabc\nabc',
//'a b c def' | 'a b c\ndef'
但是我无法弄清楚如何通过第二个(&#39; abc abc abc&#39;);
它必须是纯粹的javascript。
任何指针?
感谢。
答案 0 :(得分:2)
答案似乎是:
function wordWrap(str, cols) {
var formatedString = '',
wordsArray = [];
wordsArray = str.split(' ');
formatedString = wordsArray[0];
for (var i = 1; i < wordsArray.length; i++) {
if (wordsArray[i].length > cols) {
formatedString += '\n' + wordsArray[i];
} else {
if (formatedString.length + wordsArray[i].length > cols) {
formatedString += '\n' + wordsArray[i];
} else {
formatedString += ' ' + wordsArray[i];
}
}
}
console.log(formatedString);
}
wordWrap('abcdef abcde abc def', 5);
wordWrap('abc abc abc', 5);
wordWrap('a b c def', 5);
你可以在这里看到jsfiddle https://jsfiddle.net/ticuclaudiu/yh269rc0/13/
答案 1 :(得分:0)
你可以尝试使用像这样的正则表达式
var input = [
'abcdef abcde abc def',
'abc abc abc',
'a b c def'
];
var output = input.map(function(val){
return val.replace(/(^|[ ])[^ ]{2,}([ ]|$)/g,function(val2){
return val2.replace(' ','\\n')
})
})
console.log(output) // ["abcdef\nabcde\nabc\ndef", "abc\nabc\nabc", "a b c def"]