A space is utilized to separate words in a sentence. The addition of space makes the entire sentence meaningful. But to make the content more readable, a new line is used. To move content to the next line, use the new line character (\n).
For replacing space with the new line, you can use the given mentioned methods:
Let’s look at the working of each method.
Method 1: Replace Space with New Line Using replace() Method
The “replace()” method replaces the value in a string with the specified string or a character. It is the predefined method of the String type object. It returns a new string as output with the replaced values after searching the string for a specific value or a regex pattern.
In our case, we will use a new line to remove the space in a string.
Follow the below-given syntax to use the replace() method:
The given method takes two parameters; one is the “searchValue” that will be searched in a string and needs to be replaced, and the other is the “replaceValue” that is used as a replacer. For instance, the space is the replaced value that will be searched in a String, and the new line is its replacer.
Example 1: Replacing Single Space with New Line
In this example, we will first create a string type variable to store a string with spaces:
Then, call the replace() method by passing the space (“ ”) as the replaced value going to be searched in the String and the new line “\n” is passed as the replacer:
Output shows that the replace() method only replaces the first occurrence of space with the new line while the string contains two spaces:
If you want to replace all the occurrences of the spaces with a new line in a string, follow the next given section.
Example 2: Replacing Multiple Spaces with New Line
Here, we will consider the same string as in the previous example and replace all the spaces with the new line using the regex pattern “/ /g” in the replace() method:
In the regex pattern, we have added the “g” (global) flag, for matching all the occurrences of the spaces in a string.
As you can see, the output indicates that all the spaces are successfully replaced with a new line. Every word after the space starts from a new Line:
If you want to perform the same operation without using the regex, then use the below-discussed method.
Method 2: Replace Space with New Line Using replaceAll() Method
There is another method for replacing something from a string called the “replaceAll()” method. In the replaceAll() method, you do not need to add a regex for replacing all the instances of a specific character in a string. This method also accepts two parameters one is the searched value, and the other is its related replacer.
Follow the given syntax to use the replaceAll() method:
In this example, we will use the same string created in the previous example and then replace all the spaces with the new line without using any regex pattern:
As you can see that all words after the spaces are now moved to the new line: