About

CSS (3)

JavaScript (6)

Web browsers (2)

 

Blog

JavaScript

The scenario for this script is if you have some long text content where the only way to differentiate between paragraphs are a line break. The purpose of this script is to wrap every text entity separated by line breaks within p tags.

Input text
This is some text that is inserted as a long paragraph without any line breaks.
And suddenly, a line break in the input code!
Isn't this amazing?
Output code
<p>This is some text that is inserted as a long paragraph without any line breaks.</p>
<p>And suddenly, a line break in the input code!</p>
<p>Isn't this amazing?</p>
Convert the text to paragraphs.

The script

function textToParagraphs(){
	if(document.getElementById && document.getElementById("input-text")){
		/*
			The non-standard innerHTML property is used instead of the recommended 
			textContent one, for greater web browser compliance in this example
		*/	
		var strInputText = document.getElementById("input-text").innerHTML;		
		var strText = "<p>" + strInputText.replace(/\n([^$])/g, "</p>\n<p>$1") + "</p>";
		alert("Input text:\n" + strInputText + "\n\nOutput code:\n" + strText);	
	}	
}