I've adapted a PHP script lifted from another project to use in JavaScript, this script works great for shortening text to a set limit. I would like to use it to also split it to multiple parts if it is over the set limit.
The current code which shortens once is here: /
Here's what I have so far: / (I'm pretty sure I'm not doing it right)
I have gotten stuck in loops a few to many times, I'm not sure how to proceed with it.
function strTruncate($string, $your_desired_width) {
arr = [];
if (typeof($last_part)) {
$last_part = 0;
}
$parts = $string.split(/([\s\n\r]+)/);
$parts_count = $parts.length;
$length = 0;
$last_part = 0;
for (; $last_part < $parts_count; ++$last_part) {
$length += $parts[$last_part].length;
if ($length > $your_desired_width) {
break;
}
}
$start_part = 0;
return $parts.slice($start_part, $last_part).join('');
}
Shorten Once Result:
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer malesuada, est ut interdum ullamcorper, metus lorem interdum ipsum, vitae
New Expected Result:
array[0] = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer malesuada, est ut interdum ullamcorper, metus lorem interdum ipsum, vitae",
array[1] = "vulputate ante quam ut augue. Praesent sit amet varius lorem. Aliquam odio nunc, mattis in mollis vitae, laoreet non velit. Curabitur"
array[2] = "adipiscing, nisl tincidunt consequat ornare, ligula mauris sed."
I've adapted a PHP script lifted from another project to use in JavaScript, this script works great for shortening text to a set limit. I would like to use it to also split it to multiple parts if it is over the set limit.
The current code which shortens once is here: http://jsfiddle/WilliamIsted/P5jxK/
Here's what I have so far: http://jsfiddle/WilliamIsted/UkhXL/ (I'm pretty sure I'm not doing it right)
I have gotten stuck in loops a few to many times, I'm not sure how to proceed with it.
function strTruncate($string, $your_desired_width) {
arr = [];
if (typeof($last_part)) {
$last_part = 0;
}
$parts = $string.split(/([\s\n\r]+)/);
$parts_count = $parts.length;
$length = 0;
$last_part = 0;
for (; $last_part < $parts_count; ++$last_part) {
$length += $parts[$last_part].length;
if ($length > $your_desired_width) {
break;
}
}
$start_part = 0;
return $parts.slice($start_part, $last_part).join('');
}
Shorten Once Result:
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer malesuada, est ut interdum ullamcorper, metus lorem interdum ipsum, vitae
New Expected Result:
array[0] = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer malesuada, est ut interdum ullamcorper, metus lorem interdum ipsum, vitae",
array[1] = "vulputate ante quam ut augue. Praesent sit amet varius lorem. Aliquam odio nunc, mattis in mollis vitae, laoreet non velit. Curabitur"
array[2] = "adipiscing, nisl tincidunt consequat ornare, ligula mauris sed."
Share
Improve this question
edited Nov 21, 2012 at 19:37
William Isted
asked Nov 21, 2012 at 19:32
William IstedWilliam Isted
12.3k4 gold badges33 silver badges46 bronze badges
3
- 1 Please post your code here, not on some unrelated page. An additional demo is nice, but the relevant code belongs to the question. – Bergi Commented Nov 21, 2012 at 19:36
-
2
Please, replace all uses of
.count()
with.length
. It hurts :-) – Bergi Commented Nov 21, 2012 at 19:37 -
@Bergi Good call, I tried
.length()
before, obviously that didn't work. – William Isted Commented Nov 21, 2012 at 19:40
4 Answers
Reset to default 4Your code is a bit messy, it can be rewritten to something like this
function strTruncate(string, width) { // your original function
string = string.replace(/[\s\r\n]+/, ' ');
if(string.length >= width) {
return string[width-1] === ' ' ? string.substr(0, width - 1) : string.substr(0, string.substr(0, width).lastIndexOf(' '));
}
return string;
}
function strTruncateWhole(string, width) { // function that stores result(s) in array
arr = [];
string = string.replace(/[\s\r\n]+/, ' ');
var b = 0;
while(b < string.length) {
arr.push(strTruncate(string.substring(b), width));
b += arr[arr.length-1].length;
}
return arr;
}
I believe what you're looking for is a script like this:
function strSplitOnLength(data, your_desired_width) {
if(data.length <= 0)
return []; // return an empty array
var splitData = data.split(/([\s\n\r]+)/);
var arr = [];
var cnt = 0;
for (var i = 0; i < splitData.length; ++i) {
if (!arr[cnt]) arr[cnt] = ''; //Instantiate array entry to empty string if null or undefined
if (your_desired_width < (splitData[i].length + arr[cnt].length))
cnt++;
arr[cnt] += splitData[i];
}
return arr;
}
strSplitOnLength('Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer malesuada, est ut interdum ullamcorper, metus lorem interdum ipsum, vitae vulputate ante quam ut augue. Praesent sit amet varius lorem. Aliquam odio nunc, mattis in mollis vitae, laoreet non velit. Curabitur adipiscing, nisl tincidunt consequat ornare, ligula mauris sed.', 140);
Just go on with the loop. Instead of breaking and returning the parts from start
to last
only, splice them out of the array, reset your width count and push them on a result array.
Also notice that other than in PHP you need to declare all local variables with var
; and also there is no boolean typeof
function but a keyword that returns the string "undefined"
(not sure what you wanted to do there anyway).
function strTruncate(str, maxWidth) { // not sure whether that's the best name
var resultArr = [];
var parts = str.split(/([\s\n\r]+)/);
var count = parts.length;
var width = 0;
var start = 0;
for (var i=0; i<count; ++i) {
width += parts[i].length;
if (width > maxWidth) {
resultArr.push( parts.slice(start, i).join('') );
start = i;
width = 0;
}
}
return resultArr;
}
var str='Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer malesuada, est ut interdum ullamcorper, metus lorem interdum ipsum, vitae.';
var parts=4
console.log(divideText(str,parts))
function divideText(text, parts) {
var split=/[\s\n\r]/g
return text.split(split).reduce((arr, el, i) => {
const index = Math.floor(i * parts / text.split(split).length);
arr[index] = arr[index] ? arr[index] + " " + el : el;
return arr;
}, []);
}