This manual will guide you about replacing a character with a new line in JavaScript.
How to Replace a Character with New Line in JavaScript?
To replace a character with a new line in JavaScript, you can use:
We will now go through each of the two approaches one by one!
Method 1: Replace a Character with New Line in JavaScript Using “replace()” Method
The “replace()” method searches for a specific value in the given string and replaces it. This method can be applied to replace a specific character with a new line.
Syntax
Here, “searchValue” will be replaced with the “newValue” in the given string.
Example 1: Replace “!” with New Line
First, include a heading in the “<h>” tag and a button and specify its id:
<button id= "button">Replace the Character</button>
Apply the “document.querySelector()” method and access the button using its “id” and heading respectively:
let head= document.querySelector("h");
Next, initialize a variable named “str” with a value and set it as the inner text of “head”:
head.innerText= str;
After that, apply an event “click” and utilize the replace() method to replace the specific character “!” with a new line specified as “\n”. Lastly, display the corresponding string value after replacing the character:
let result= str.replace("!","\n");
head.innerText = result;
});
When the added button is clicked, “!” will be replaced with the new line which can be seen below:
Example 2: Using regex for Replacing “!” with New Line
In this example, we will utilize the “/!/g” regex for replacing all of the matches “!” with the new line in the provided string. This regex will be then passed to replace() method as an argument along with the “\n” new line character:
let regExp= /!/g;
let result= str.replace(regExp, "\n");
head.innerText = result;
});
The corresponding output in this case will be:
Method 2: Replace a Character with New Line in JavaScript Using “replaceAll()” Method
Do you not want to use regex? No worries! The “replaceAll()” method gets you covered. This method can be used for removing all the specified characters, which will yield the same output as the previous example.
let result= str.replaceAll("!","\n");
head.innerText = result;
});
Output
We have discussed different creative methods to replace a character with a new line in JavaScript.
Conclusion
To replace a character with a new line in JavaScript, the “replace()” method can be utilized to replace a particular character, regex pattern with replace method to search for a specified character and replace it. Moreover, the “replaceAll()” can also be used to replace all the specific characters present in the added string. This write-up discussed the procedure to replace a character with a new line in JavaScript.