Home > Net >  Extracting filename with javascript
Extracting filename with javascript

Time:02-15

I'm trying to learn how to write a few rows of code in javascript on splitting a filename and extracting only certain characters.

For example I have a filename: "bk_is_great_2022119205974100_8Y.xlsx"

and I want to extract/display only 202211 from the filename.

var  Type = function getFourthPart (str){
     return str.split('_')][0,6];
}

How would I go about doing this? I've tried looking for answers but so far nothing that points toward what I'm looking for and this is all I've managed to create with my limited knowledge.

CodePudding user response:

If you are trying to display only 5 letters of the date from the filename always, then you can use the below statement to extract only those parts.

a.split('_')[3].substring(0,6)

CodePudding user response:

You might use a regex to match the first 3 occurrences of an underscore and right after that capture 6 digits in capture group 1.

^(?:[^\s_]*_){3}(\d{6})

In parts the pattern matches:

  • ^ Start of string
  • (?:[^\s_]*_){3} Repeat 3 times matching optional non whitespace chars except _ and then match _
  • (\d{6}) Capture group 1, match 6 digits

const s = "bk_is_great_2022119205974100_8Y.xlsx";
const regex = /^(?:[^\s_]*_){3}(\d{6})/;
const m = s.match(regex);

if (m) {
  console.log(m[1]);
}

  • Related