Reputation: 13
I have a txt file with 20.000 lines, and I want to add a word at the beginning of every line.
Example :
Original file
A
B
C
D
I want to make it look like this
Y A
Y B
Y C
Y D
Is there any solution with JavaScript code ?
Upvotes: 0
Views: 161
Reputation: 149050
This should work:
var input = "A\nB\nC\nD";
var output = input.split("\n")
.map(function(s) { return "Y " + s; })
.join("\n");
But for 20,000 lines, this won't be terribly efficient. It's probably better if you can read the file one line at a time server side, and write the result to the output stream one line a time.
Also note, the map
function was introduced in ES5, so it won't be available in some older browsers. You can polyfill it, or use this alternative suggested by gilly3:
var output = "Y " + input.split("\n").join("\nY ");
Upvotes: 1
Reputation: 767
A bit of regex:
str =
'a\n'+
'b\n'+
'c\n'+
'd';
str.replace(/^/mg, 'prefix ')
/*
prefix a
prefix b
prefix c
prefix d
*/
Upvotes: 0