Beno Odr
Beno Odr

Reputation: 1273

Find file name in list with extension

I need to find the following filename pattern if it exist return true in nodejs I need the the pattern will return true in case the following name

Makefile
makefile
makefile.ext
makefile.abc

after the dot it can be any name...what is importent that it start with makefile

I've tried with the following but this give just the ext not the orig file name

var patt1 = /\.([0-9a-z]+)(?:[\?#]|$)/i;

var m1 = ("makefile").match(patt1);
alert(m1);  

Any idea?

Upvotes: 0

Views: 103

Answers (4)

Drew Reese
Drew Reese

Reputation: 202751

Simple regex to test if a string starts with specified "makefile" prefix.

Searches for matches of a string that start and end exactly with "makefile" OR starts with "makefile." and ignores all after the period. The i after the pattern is a flag that indicates it is a case-insensitive search, meaning upper and lowercase, and any mix between, characters can match.

/(^makefile$|^makefile\.)/i.test(filename);

const isMakefile = filename => /(^makefile$|^makefile\.)/i.test(filename);

const filenames = [
  "Makefile",     // true
  "makefile",     // true
  "makefile.ext", // true
  "makefile.abc", // true
  "nakeFile.abc", // false
  "makefil",      // false
  "makefiles",    // false
  "makefiles.abc" // false
];

filenames.forEach(filename => console.log(filename, isMakefile(filename)));

Edit spring-sea-u4fmq

Upvotes: 2

Suman Kumar Dash
Suman Kumar Dash

Reputation: 704

Why don`t you simply use this one?

var n = str.toLowerCase().startsWith("makefile")
if(n===true){
//write your code
}

Upvotes: 1

Alan Paul Mathew
Alan Paul Mathew

Reputation: 219

This will work. Put the file name to the constant fileName

const fileName = "The file name to test";
return fileName.startsWith("Makefile.");

Upvotes: 1

Strille
Strille

Reputation: 5781

Since you don't care about any content after the dot, just split the filename into an array using the dot as the separator.

The first element of the resulting array will always be the string up to the dot (or the whole string if there was no dot in the filename).

Then you can covert the string to lowercase and make the comparison:

function isMakeFile(filename) {
    return filename && filename.split('.')[0].toLowerCase() === 'makefile';
}

console.log(isMakeFile('Makefile')); // true
console.log(isMakeFile('makefile')); // true
console.log(isMakeFile('makefile.ext')); // true
console.log(isMakeFile('makefile.abc')); // true

Upvotes: 1

Related Questions