简体   繁体   中英

How to keep line breaks when using .text() method for jQuery?

I'm trying to achieve a typewriting effect and my content consists of a lot of HTML entities. The problem with using .html() is that since it writes out each letter at a time, it will type out & then l then t then ; and finally it would change to < .

HTML

<p id="src">
&lt;!DOCTYPE html&gt;
&lt;!--[if lt IE 7]&gt;      &lt;html class=&quot;no-js lt-ie9 lt-ie8 lt-ie7&quot;&gt; &lt;![endif]--&gt;
&lt;!--[if IE 7]&gt;         &lt;html class=&quot;no-js lt-ie9 lt-ie8&quot;&gt; &lt;![endif]--&gt;
&lt;!--[if IE 8]&gt;         &lt;html class=&quot;no-js lt-ie9&quot;&gt; &lt;![endif]--&gt;
&lt;!--[if lt IE 9]&gt;      &lt;html class=&quot;no-js lt-ie9&quot;&gt; &lt;![endif]--&gt;
</p>
<p id="typed-paragraph">
    <span id="target"></span>
    <span id="typed-cursor">|</span>
</p>

CSS

#src {
    display: none;
}

jQuery

(function(){
    var srcText = $("#src").html();
        i = 0;
        result = srcText[i];
    setInterval(function() {
        if(i == srcText.length-1) {
            clearInterval(this);
            return;
        };
        i++;
        result += srcText[i].replace("\n", "<br />");
        $("#target").html(result);
    }, 150); // the period between every character and next one, in milliseonds.
})();

You can see the example of it here http://jsfiddle.net/j9KF5/9/

But if I use .text() then I lose all the line breaks.

Ultimately, how I can either fix the entities problem or the line break problem?

You don't need to worry about the HTML entities nor any complex string replacing.

All you need is a little CSS:

#target {
    white-space: pre;
}

and use the .text() approach:

(function(){
    var srcText = $("#src").text().trim();
        i = 0;
        result = srcText[i];
    setInterval(function() {
        if(i == srcText.length-1) {
            clearInterval(this);
            return;
        };
        i++;
        result += srcText[i];
        $("#target").text(result);

    }, 150); // the period between every character and next one, in milliseonds.
})();

http://jsfiddle.net/mattball/vsb9F/

To anyone who's looking for what the title of the question actually asks (this is how I got to this page, "how to keep line breaks when using jQuery's text() method"), you can use something like this:

(function($){
   $.fn.innerText = function(msg) {
         if (msg) {
            if (document.body.innerText) {
               for (var i in this) {
                  this[i].innerText = msg;
               }
            } else {
               for (var i in this) {
                  this[i].innerHTML.replace(/&amp;lt;br&amp;gt;/gi,"n").replace(/(&amp;lt;([^&amp;gt;]+)&amp;gt;)/gi, "");
               }
            }
            return this;
         } else {
            if (document.body.innerText) {
               return this[0].innerText;
            } else {
               return this[0].innerHTML.replace(/&amp;lt;br&amp;gt;/gi,"n").replace(/(&amp;lt;([^&amp;gt;]+)&amp;gt;)/gi, "");
            }
         }
   };
})(jQuery);

Now call $('.some-class').innerText() to get the text with line breaks preserved.

Why not use .replace on the srcText variable.

srcText = srcText.replace(/&lt;/g, "<"); //performs this with global modifier to cover whole string

Placing a series of .replace calls inside a function, with each call modified to a different character would sanitise the whole string before you print it to the screen.

I would recommend using .innerText rather than implementing a complex loop in the other answers, since it saves you so much more time. To do so, simply do $(selector)[0].innerText .

Here's a demo. Begin typing into the input. Make sure to add new lines and see how innerText preserves them!

 var jquerytext = $('.jQuerytext'); var innerText = $('.innerText'); $('.text').on('input', function(){ jquerytext.text($(this).text()); innerText[0].innerText=($(this)[0].innerText); })
 pre{ display:inline; } .text{ border:2px solid black; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="text" contenteditable="true" spellcheck="false">Hello World! Begin typing in here, and make sure to press Enter to make new lines! </div> <h2>jQuery <pre>.text()</pre></h2> <div class="jQuerytext"> Begin typing in here, and make sure to press Enter to make new lines! </div> <h2>Vanilla <pre>.innerText</pre></h2> <div class="innerText"> Begin typing in here, and make sure to press Enter to make new lines! </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM