JavaScript/Line reverser

To reverse the lines of a string, one needs to verify whether the data that was fed into the function is a string. This is done using the typeof() function. If the data is a number, it will be returned without being processed, since pure numbers can only be in one line.

Then, the length of the first line is detected, so the line can be extracted from the input string using the substring() function, and appended to the variable that will be returned after being built.

After the first line of the input string is appended to the output variable, the first line and the first line break will be cut off from the input string. This process is repeated until there are no more lines left in the input string.

The last input and output are memorized in the line_reverser_last_input and line_reverser_last_output variables respectively, so they can be re-used without having to run the line reverser function again.

Source code edit

function line_reverser(input) {
 	/* initialize variables */
 	var input_string = "";
 	var output_string = "";

	/* exit if input is not a string or number; single-line texts or numbers will return as same text */
	if (typeof(input) != "string" && typeof(input) != "number") return false;
		else input_string = input;
		line_reverser_last_input = input;
	if (typeof(input) == "number") return input;

 	while (input_string.search(/\n/) > -1 || input_string.length > 0) /* repeat until no more line breaks */ {
		/* determine length of first line */
		var line_1_length=input_string.search(/\n/);
		if(line_1_length == -1) /* no new lines exist */ {
			line_1_length = input_string.length;
		}

		/* put text of first line in a variable */
		var line_1=input_string.substring(0,line_1_length);

		/* build variable with reversed lines; prevent adding a blank line at the end */
		if (output_string.length == 0) output_string = line_1;
			else output_string = line_1 + "\n" + output_string;

		/* cut off first line and the first line feed from input string */
		input_string = input_string.substring(line_1_length+1);

	}
	/* memorize last output for later use */
	line_reverser_last_output = output_string; 

	return output_string;

}

/* initializing blank string variables to memorize last inputs and outputs for later use */
var line_reverser_last_input = "";
var line_reverser_last_output = "";

Try it out edit

You can test the code by first loading it by pasting it into the console of the web development tools on a desktop computer or laptop web browser, or into the URL bar of a mobile web browser after javascript:.

After having loaded the script, enter javascript:alert("line 1 \n line 2") in the URL bar or the web development tools. \n is a line feed. The lines will be returned reversedly.