0

Let's say I have a large wall of text that I've pasted onto my page inside a div with id "story". Each paragraph is actually on a single line in the html file, and each paragraph is separated by a single line. I want to make the wall of text more readable using bootstrap. I've set the css in a blog like format, is there any way to dynamically add </p><p> at every paragraph separation?

5
  • at first blush I'd look at the :after css selector. Commented Jul 24, 2014 at 23:02
  • 1
    Why not just add a margin or padding to the p elements already there? Commented Jul 24, 2014 at 23:02
  • I think the question is how to add <p>s to the document. Commented Jul 24, 2014 at 23:03
  • If you used <pre> instead of <div> you could replace the new line characters with <p> tags, but that feels perhaps a little hacky. Commented Jul 24, 2014 at 23:04
  • @dave sorry, there aren't any tags at all in the wall of text. I've added the first one at the top and the last closing one at the bottom myself. Just want to add </p><p> in between the paragraphs now. Commented Jul 24, 2014 at 23:16

2 Answers 2

1
var paragraphs = "your text".split(/\n\s*\n/);//since paragraphs are separated by
for(var i = 0; i < paragraphs.length; i++){   //a line, we need two \n here.
    var p = document.createElement("p");
    p.innerHTML = paragraphs[i].trim();
    document.querySelector("#story").appendChild(p);
}

//==============
//To get the text of an element (with new lines), you can do this:
document.querySelector("#story").childNodes[0].wholeText;

Maybe something like this? http://jsfiddle.net/DerekL/qv2GZ/

What you shouldn't do is replacing text inside a string and dumping it right into DOM. That's bad practice. That's why here I'm creating a p element instead of replace lines with </p><p>.

Sign up to request clarification or add additional context in comments.

Comments

0

I think that you should take a look here: How do I replace all line breaks in a string with <br /> tags?

And here: How to replace all occurrences of a string in JavaScript?

Remember that new line is simply \n. Then it is a matter of simple string replace. There is a huge research about it, and the question is a possible duplicate, so I think that is enough to answer :).

Best regards!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.