I need to check if file name suffix is type JavaScript (JS files end with *.js) for that I use the following code which works
var ext = aa.getName().substr(aa.getName().lastIndexOf('.') + 1);
Now the problem is that if the file is named file2.json
I'm still getting true (it's return json)
My question is if there a better way to do it i.e. given any file name like
file1.xml
, file2.js
, file3.json
or file4.html
, it will return true just for file2
.
I need to check if file name suffix is type JavaScript (JS files end with *.js) for that I use the following code which works
var ext = aa.getName().substr(aa.getName().lastIndexOf('.') + 1);
Now the problem is that if the file is named file2.json
I'm still getting true (it's return json)
My question is if there a better way to do it i.e. given any file name like
file1.xml
, file2.js
, file3.json
or file4.html
, it will return true just for file2
.
-
/.*\.js$/
or/\.js$/
should work, but where do you do this? node or browser? – baao Commented Aug 6, 2017 at 14:03 - @baao - I use it in the browser – Jenny Hilton Commented Aug 6, 2017 at 14:04
6 Answers
Reset to default 3I believe this can work
function check(str){
if(str.match(/(\w*)\.js$/) == null){
console.log('false');
return false;
}
else {
console.log('true');
return true;
}
}
check('file1.xml');
check('file2.js');
check('file3.json');
check('file4.html');
let isJS = function(filename) {
return /\.js$/i.test(filename)
}
console.log(isJS("asd.json")) // false;
console.log(isJS("asdjs")) // false;
console.log(isJS("asd.js")) // true;
console.log(isJS("asd.JS")) // true;
You could check if string ends with .js
with the following function:
function isJavascriptFile(str) {
var regex = /\.js$/;
var match = str.match(regex);
return match !== null;
}
According to your code you would use it like this:
var name = aa.getName();
isJavascriptFile(name);
I think for this case better not using regex,
var arr = [
'file1.xml',
'file2.js',
'file3.json',
'file4.html'
];
for(var i=0, len=arr.length; i<len; i++){
if(returnExtension(arr[i]) == 'js') {
alert('Your file is: ' + arr[i])
}
}
function returnExtension(filename){
var a = filename.split(".");
if( a.length === 1 || ( a[0] === "" && a.length === 2 ) ) {
return "";
}
return a.pop();
}
my working example is here https://jsfiddle/gat8mx7y/
You've to modify your code a little bit, you're almost right:
funciton isJavascriptFile(fileName){
var ext = fileName.substr(fileName.lastIndexOf('.') + 1);
if(ext === 'js'){ return true; }
return false;
}
if(isJavascriptFile(aa.getName()) ) {
console.log("file is javascript");
}
//function GetJSName(){
var filename="sample.js";
var name = filename.split('.')[0];
alert(name);
//};
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745405488a4626294.html
评论列表(0条)