Javascript - Add line numbers.


Javascript - Add line numbers. This program adds line numbers at the start of each line.

CODE
<!--JQuery Reference Library--> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script> <script> function addLineNumbers(){ inputText = "Apple\nBanana\nOrange"; // Provide the input text here. var lines = inputText.split("\n"); //Split the input based on the new line character. var resultArray = []; //Loop through the splitted lines. var i = 1; //This variable handles the line numbering. $.each(lines, function(){ resultArray.push(String(i) + ". " + String(this)); //Add line number at the start of the line and push it to the result array. i++; }); var result = resultArray.join("\r\n"); //Join all the array elements with a new line character. alert(result); } addLineNumbers(); //Output //1. Apple //2. Banana //3. Orange </script>

Comments