Reputation: 3
I have a file that contains employee numbers alongside the employee name and then the department. It looks like this:
0234569884566781DOE, JOHN K KF ("KF" is the department)
2487231227879636WHITE, ERIC C KF
0234569884566781DOE, JOHN KRT ("RT" is the department. Some do not have a space after the middle initial like the first two examples)
and so on.
I am trying to do a substring where the output is the employees full name i.e. DOE, JOHN K. How would I set up the substring to only get the full name and nothing else?
The starting position will always be 16 because the employee number is always 16 digits. But I am not sure what the end position would be because the name obviously differs in length for each person.
Upvotes: 0
Views: 211
Reputation: 18888
You can use a little bit of regex to accomplish this:
const employees = [
"0234569884566781DOE, JOHN K KF",
"2487231227879636WHITE, ERIC C KF",
"2487231227879636BLACK, JANE CRF"
];
const regex = /^\d+([a-z, ]+?) ?[a-z]{2}$/i;
const names = employees.map(data => data.match(regex)[1]);
console.log(names);
Upvotes: 0
Reputation: 952
Here is one way
const pieces = '2487231227879636WHITE, ERIC C KF'.split(' ')
pieces.pop() // remove department
const lastName = pieces[0].substr(16)
pieces.reverse()
pieces.pop() // remove first name with employee num prefix
const name = lastName + pieces.join(' ')
Upvotes: 0
Reputation: 4768
Hope this helps,
const staff = [
"0234569884566781DOE, JOHN K KF",
"2487231227879636WHITE, ERIC C KF",
"2487231227879636BLACK, JANE CRF"
];
const names = staff.map(line => {
let n = line.substring(16);
n = n.substring(0, n.length-2);
return n.trim();
});
console.log(names);
Upvotes: 1