'Javascript - Add a comma after every line break

I have a .txt file full of strings that look like the ones beneath. I need to add a comma at the end of every line. At the moment it looks like this:

name,age ----> usa
name,age ----> uk
name,age ----> de

And after it should look like this:

name,age ----> usa,
name,age ----> uk,
name,age ----> de,


Solution 1:[1]

You can use regex

var str = `name,age ----> usa
name,age ----> uk
name,age ----> de`;
var str2  = str.replace(/(\n)/g,",\n") + ",";

Solution 2:[2]

Yes use regex, but the above answer is incorrect (it results in \n at the start of each line).

var str = `name,age ----> usa
name,age ----> uk
name,age ----> de`;

var str2  = str.replace(/(?:\r\n|\r|\n)/g, ',');

The output will be:

'name,age ----> usa,    name,age ----> uk,    name,age ----> de'

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 huydq5000
Solution 2 Waldo Frank