sw45acp Posted June 1, 2010 Share Posted June 1, 2010 Hi, I wish to write a function to word-wrap a string to a certain width, and if a word breaks that width, I want it to reverse course and find the nearest space, so that way no words are broken apart. I've gotten far, I just can't figure out how to go backwards with it. function wordWrap(string,width) { var output = ''; for (var i = 0; i < string.length; i ++) { output += string.substr(i,1); if (i == width) { if (string.charAt(i) == ' ' ) { output += '<br />'; }else{ //go backwards and try to find a space //HOW?? } } } alert(output); } Thank you for your help. Link to comment https://forums.phpfreaks.com/topic/203478-an-almost-complete-wordwrap-function/ Share on other sites More sharing options...
sw45acp Posted June 1, 2010 Author Share Posted June 1, 2010 I've gotten a little bit farther... function wordWrap(string,width) { var output = ''; for (var i = 0; i < string.length; i ++) { output += string.substr(i,1); if (i == width) { if (string.charAt(i) == ' ' ) { output += '<br />'; }else{ //takes the current position and pulls out everything before it var part = string.substr(0,i); //from that string, pulls out the last space var pos = part.lastIndexOf(' '); //show it alert(pos); //how to insert it into that position? } } } alert(output); } var stuff = "one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen"; wordWrap(stuff,20); Link to comment https://forums.phpfreaks.com/topic/203478-an-almost-complete-wordwrap-function/#findComment-1065966 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.