Home > Software engineering >  Extract id from generated file name
Extract id from generated file name

Time:11-15

I am trying to extract the user id from generated file name. First I wrote them as :

id_timestamp.ext

And now I need to read the list and filter out of the list of files only specific user with the id owned files.

I think doing

substring(fileName, id.length)

is to wonky.

Is there a way to do it ? Should I use a regex?

CodePudding user response:

You could use a regex to solve your problem.

const filename = 'id_timestamp.ext';
const regex = /^(\w )_timestamp\.ext$/;
const id = filename.match(regex)[1];

This works by matching the id part with a capturing group. This group can than be used as the id as it only contains the id part.

Alternatively you can use a combination of indexOf to find the position of the underscore and substring to get the first part up to that position.

const filename = 'id_timestamp.ext';
const id = filename.substring(0, filename.indexOf("_"))

If the id always has the same length then you even can get rid of the indexOf part.

CodePudding user response:

Assuming you built your filenames like

const filename = `${id}_${timestamp}.ext`;

and assuming that your ids and timestamps don't contain timestamps (so that the generated filenames are unambiguous), you can check whether a file belongs to a certain user via

filename.startsWith(`${id}_`)

Notice you need to include the underscore, just filename.startsWith(id) will lead to false positives as your ids are unlikely to be prefix-free.

CodePudding user response:

If your id will always be the first and you are generating as id_timestamp.ext pattern I suggest the following approach to extract out id from the file name

const fileName = `1234_file.txt`;
const arr = fileName.split("_");
const id = arr[0];

console.log(id) // "1234"
  • Related