2

I have this in a Div (Text actually "wraps" because Div box has short width; except where line breaks are intentional):

"Now is the time
for all good men
to come to the aid
of their country"

"The quick brown fox
jumps over the
lazy dogs"

I would like this:

lazy dogs"
jumps over the
"The quick brown fox"

of their country"
to come to the aid
for all good men
"Now is the time

I've tried using Reverse(); but am not getting the desired results.

Note: I'm not trying to reverse a string per say, but actual lines of text (ie: sentences).

C King
  • 281
  • 1
  • 5
  • 14
  • Are the line breaks within the string? – Mottie Jan 18 '14 at 22:28
  • Please post actual HTML you're using, not sure if you have line breaks there (making your request easy) or just text wrapping. (making it complicated) – Shadow The GPT Wizard Jan 18 '14 at 22:34
  • @Mottie -- No, no line breaks at end of lines. Only where spacing is concerned. I imagine if I had line break after each line, I could use them as delimiters. But lines just wrap. – C King Jan 18 '14 at 22:46
  • @ShadowWizard -- Responded above. So, likely complicated. – C King Jan 18 '14 at 22:49
  • @CKing so [is this the actual textarea you're using](http://jsfiddle.net/xdg6H)? – Shadow The GPT Wizard Jan 18 '14 at 22:54
  • @ShadowWizard -- Yes, similar. Except I'm using CSS to assign width. In Context, I'm reading what's in TextArea and outputting to a DIV Element. Simple enough. DIV is a fixed width and Font Size is very large. Hence, the lines automatically wrap. I'm trying to figure out where the lines wrap inside the DIV. Guess if I could figure that out - the rest will fall into place. – C King Jan 18 '14 at 23:04
  • @ShadowWizard - Realized error. Corrected desired display output. See original problem above. – C King Jan 18 '14 at 23:20
  • Awesome! There's no way I would have come up with that. Thanks! – C King Jan 19 '14 at 03:08

3 Answers3

2

If you got line breaks like this \n, you can do the following:

var lineBreak = "\n",
    text = "Now is the time\nfor all good men\nto come to the aid\nof their country";

text = text.split(lineBreak).reverse().join(lineBreak);

If the line break is another sign, change the variable lineBreak.

friedi
  • 4,350
  • 1
  • 13
  • 19
0

warning, this is pseudo code :

  lines=[];
  index=0;
  start=0;
  for(characters in alltext){
    if(newLine){
        lines.push(alltext.substring(start,index);
        start=index;
    }
    i++
  }      
  sortedLines=[]
  for(var i=lines.length;i>-1;i--){
     sortedLines.push(lines[i]);
     html=$('selector').html();
     html+=lines[i];
     $('selector').append(html);
  }

better use split

john Smith
  • 17,409
  • 11
  • 76
  • 117
0

OK, got it eventually. Based on this answer of mine, I came up with a code that identifies the actual lines inside textarea, even when wrapped.

Next step was to translate div into textarea so we can use the above trick.

Having this, it's simple matter of manipulating the lines using .reverse() method.

Final code is:

$("#btnInvert").click(function() {
    var placeholder = $("#MyPlaceholder");
    if (!placeholder.length) {
        alert("placeholder div doesn't exist");
        return false;
    }

    var oTextarea = $("<textarea></textarea>").attr("class", placeholder.attr("class")).html(placeholder.text());
    oTextarea.width(placeholder.width());

    //important to assign same font to have same wrapping
    oTextarea.css("font-family", placeholder.css("font-family"));
    oTextarea.css("font-size", placeholder.css("font-size"));
    oTextarea.css("padding", placeholder.css("padding"));

    $("body").append(oTextarea);

    //make sure we have no vertical scroll:
    var rawTextarea = oTextarea[0];
    rawTextarea.style.height =  (rawTextarea.scrollHeight + 100) + "px";

    var lines = GetActualLines(rawTextarea);
    var paragraphs = GetParagraphs(lines).reverse();
    lines = [];
    for (var i = 0; i < paragraphs.length; i++) {
        var reversedLines = paragraphs[i].reverse();
        for (var j = 0; j < reversedLines.length; j++)
            lines.push(reversedLines[j]);
        if (i < (paragraphs.length - 1))
            lines.push("");
    }
    rawTextarea.value = lines.join("\n");
    placeholder.html(rawTextarea.value.replace(new RegExp("\\n", "g"), "<br />"));
    oTextarea.remove();
});

function GetParagraphs(lines) {
    var paragraphs = [];
    var buffer = [];
    $.each(lines, function(index, item) {
        var curText = $.trim(item);
        if (curText.length === 0) {
            if (buffer.length > 0) {
                paragraphs.push(buffer);
                buffer = [];
            }
        } else {
            buffer.push(curText);
        }
    });
    if (buffer.length > 0)
        paragraphs.push(buffer);
    return paragraphs;
}

function GetActualLines(oTextarea) {
    oTextarea.setAttribute("wrap", "off");
    var strRawValue = oTextarea.value;
    oTextarea.value = "";
    var nEmptyWidth = oTextarea.scrollWidth;
    var nLastWrappingIndex = -1;
    for (var i = 0; i < strRawValue.length; i++) {
        var curChar = strRawValue.charAt(i);
        if (curChar == ' ' || curChar == '-' || curChar == '+')
            nLastWrappingIndex = i;
        oTextarea.value += curChar;
        if (oTextarea.scrollWidth > nEmptyWidth) {
            var buffer = "";
            if (nLastWrappingIndex >= 0) {
                for (var j = nLastWrappingIndex + 1; j < i; j++)
                    buffer += strRawValue.charAt(j);
                nLastWrappingIndex = -1;
            }
            buffer += curChar;
            oTextarea.value = oTextarea.value.substr(0, oTextarea.value.length - buffer.length);
            oTextarea.value += "\n" + buffer;
        }
    }
    oTextarea.setAttribute("wrap", "");
    return oTextarea.value.split("\n");
}

Just put the actual ID of your div and it should work.

Live test case.

Community
  • 1
  • 1
Shadow The GPT Wizard
  • 66,030
  • 26
  • 140
  • 208