简体   繁体   中英

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,

You can use regex

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

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM