简体   繁体   中英

insert value in javascript depending on csv cell value

I have a question on JavaScript an CSV handling:

I have a CSV File, which I parse as a string per line. For every line I have two cases on which I need to manipulate the string.

Case #1: I only need to convert the ", " with ";" to split "Name, Surname"

888;001;52;1;Name, Surname;REPVA;SomeDocname;2017-05-01;0124721CF00C0D28D2F5C44D5547D2F0.pdf;;2017-05-01;2018-07-17;888~001~52;0124721CF00C0D28D2F5C44D5547D2F0;;

this is already working with

tmp = message.toString();
var res = tmp.replace(", ",";");
message = res;
return message;

Case#2: the 3rd and 5th field are empty

888;001;;0;;REPBUCH;SomeDocname;2016-04-01;00FCC2848BA49E57490C905FB1EB4F54.pdf;;2016-04-01;2018-07-17;888~001~50;00FCC2848BA49E57490C905FB1EB4F54;;

in this case I want to fill it with a pseudo "Name, Surname" to achieve the same string format as above in Case#1.

I would add a function that cover both cases:

function checkData(message) {
    const data = message.split(";")
    if(data[2].trim() === "") data[4] = "John, Doe"; // fix only if it's missing
    return data.join(";");
}
var res = checkData(tmp);
var msg = res.replace(", ",";");
return msg;

hope it fits your needs // thanks edited your answer to match my question

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