Previously, I submitted a post in which I stated the need for a script that removed carriage returns. Its title is “Removing carriage returns.”
This script was created for me:
draft.content = draft.content.replaceAll("\n","");
After using it awhile, I realized that in some cases it was combining the last word in the line with the first word in the next line without inserting a space between the two words. Therefore, how can the above script be changed so that the issue is addressed?
There’s a lot o ways to accomplish that, but the most straightforward for is probably just doing two replace operations, the first replacing occurrences of \n (space line feed) with just a space, then replacing the remaining line feeds \n (which would not have a space before them with a space, like:
The slashes around the first argument, / *\n+ */, mean that it’s treated as a regular expression rather than as a literal string. The first two characters, space and asterisk, mean any number (including zero) of spaces. That’s followed by \n+ which means one or more newlines (a newline is the character that’s inserted when you press the Return key; you might think of it as a carriage return, but for complicated reasons newline and carriage return are different). Finally the space and asterisk at the end is just like the space and asterisk at the beginning.
So what this regular expression looks for is a line that may or may not end with some spaces, then a new line that may or may not start with some spaces. These lines may be separated by blank lines.
The second argument, ' ', is just a single space character. It’s what replaces the trailing spaces, newline, blank lines, and leading spaces found from the first argument.
Regular expressions are a kind of programming language of their own. The link @Andreas_Haberle gave is a good one for experimenting with them as you learn.