adnan_252
adnan_252

Reputation: 421

Can I insert some string at every other line using javascript?

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?

Upvotes: 0

Views: 117

Answers (2)

Derek 朕會功夫
Derek 朕會功夫

Reputation: 94339

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>.

Upvotes: 1

Jacek Kowalewski
Jacek Kowalewski

Reputation: 2851

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!

Upvotes: 0

Related Questions