Scroll for More Useful Information and Relevant FAQs
Replace comma with newline using split & join function
<script> var content = "Hello, there"; var dataArray = content.split(","); console.log(dataArray); console.log(dataArray.join("\n")); </script>
['Hello', ' there'] Hello there
['Hello', ' there']
The new line character
\nis used as a Separator to join array elements to make a string.
If we require HTML line break then we need to use
In the same way we can do following replacement
- Replace comma with space
Replace comma with HTML line break
- Replace comma with \t
- Replace character in string
In the previous example we learned to replace commas using split and join functions. It was required to do multiple manipulations to retrieve desired results.
But we have a replace function that supports regular expressions to search for patterns and replace characters accordingly.
Lets see the following example program to replace commas using replace function.
<script> var employee = "Peter, Alex, John, Camren"; employee_list = employee.replace(/,/g, '\n'); console.log(employee_list); </script>
Peter Alex John Camren
- Lets suppose we have a comma-separated employee string. Variable employees store this string.
- Here we use regular expressions with the g modifier to replace all occurrences of commas in a given string. [What if we do not use the g modifier in search terms? Please refer to below example for this]
employee.replace(/,/g, '\n')return comma replaced string from given employee names.
Each name is printed here in newline due to replace character
Replace function will replace the first occurrence of matched character from content if the regular expression is not provided.
Therefore the following program only replaces the first finding search character.
<script> var employee = "Peter, Alex, John, Camren"; employee_list = employee.replace(/,/, '\n'); console.log(employee_list); </script>
Peter Alex, John, Camren