Parsing file names with javascript

814 views javascript
4

I have file names like the following:

SEM_VSE_SKINSHARPS_555001881_181002_1559_37072093.DAT SEM_VSE_SECURITY_555001881_181002_1559_37072093.DAT SEM_VSE_MEDICALCONDEMERGENCIES_555001881_181002_1559_37072093.DAT SEM_REASONS_555001881_181002_1414_37072093.DAT SEM_PSE_NPI_SECURITY_555001881_181002_1412_37072093.DAT

and I need to strip the numbers from the end. This will happen daily and and the numbers will change. I HAVE to do it in javascript. The problem is, I know really nothing about javascript. I've looked at both split and slice and I'm not sure either will work. These files come from a government entity which means the file name will probably not be consistent.

expected output:

SEM_VSE_SKINSHARPS

SEM_VSE_SECURITY

SEM_VSE_MEDICALCONDEMERGENCIES

SEM_REASONS

SEM_PSE_NPI_SECURITY

Any help is greatly appreciated.

answered question

Maybe you should edit your post and include the expected output of those files in your example list.

1 Answer

4

This is a good use case for regular expressions. For example,

var oldFileName = 'SEM_VSE_SKINSHARPS_555001881_181002_1559_37072093.DAT',
    newFileName;
newFileName = oldFileName.replace(/[_0-9]+(?=.DAT$)/, ''); // SEM_VSE_SKINSHARPS.DAT

This says to replace as many characters as it can in the set - and 0-9, with the requirement that the replaced portion must be followed by .DAT and the end of the string.

If you want to strip the .DAT, as well, use /[_0-9]+.DAT$/ as the regular expression instead of the one above.

posted this

Have an answer?

JD

Please login first before posting an answer.