splitting strings
attempting to split a long string into smaller parts
by apasaja
HTML
<div id="splitResult"></div>
CSS
h4 {
font-family: "Trebuchet MS", Helvetica, sans-serif;
margin: 0px;
color: #FF9955;
margin-bottom: 10px;
}
p {
line-height: 18px;
font-family: "Trebuchet MS", Helvetica, sans-serif;
margin: 0px;
color: #666;
}
JavaScript
// goal: split a sentence into smaller sections - why?
// I ran into an issue with d3 where instead of being able to use the
// forgeinObject and append an html body, I had to use text node instead so
// that it work across browser and since I can't use html, I had to manual
// break long strings to clean up the presentation and ensure strings
// wouldn't overlap - my problem may also be related to the xml svg
// namespacig and a possible css name collision on the nested body tags
var mystr = "He pointed his finger in friendly jest and went over to the parapet, laughing to himself. Stephen Dedalus stepped up, followed him wearily halfway and sat down on the edge of the gunrest, watching him still as he propped his mirror on the parapet, dipped the brush in the bowl and lathered cheeks and neck.";
// Ulysess, James Joyce
// https://archive.org/stream/ulysses04300gut/ulyss12.txt
var splitStr = function(mystr){
var aStr = mystr.split(" ");
var parts = [];
var startRange = 0;
var diff = 6;
var endRange = startRange + diff;
var part = "";
for ( var i=0; i < aStr.length; i++ ){
if ( i >= startRange && i <= endRange ) {
part += aStr[i] + " ";
console.log("part: " + part + " : " + i);
}
if ( i !== 0 && ( i % diff ) === 0 || i === aStr.length - 1 ) {
parts.push(part);
var htmlStr = "<p>" + part + "</p>";
$("#splitResult").append( htmlStr );
part = "";
startRange += diff;
endRange = startRange + diff;
}
}
return parts;
}
$( "#splitResult" ).append( "<h4>Split String Test Results:</h4>" );
var parts = splitStr(mystr);