How to check if filename contains substring in JavaScript?

This question already has an answer here:

  • How to check whether a string contains a substring in JavaScript? 49 answers

  • if you have the file names you can use something like:

    if(theFileName.indexOf('myfilethree') > -1)
    {
        do your magic here because "myfilethree" is present in the name!
    }
    

    However, I am not aware of any way to read a directory index in javascript.


    There are two parts to this: getting a list of files in a directory, and then searching them for a substring. I'll start with the sceond part, because that's easiest. Simply use indexOf to check for the desired string. If the result of indexOf is not equal to -1, you have a match:

    if (filename.indexOf("myfilex") != -1) {
        // whatever you want to do
    }
    

    As to actually retrieving a list of files, you will need to use Windows Script Host and JScript. See this question for details on that.


    var str = 'myfilethree';
    if (str.toLowerCase().indexOf("myfilethree") >= 0)
    {
        alert('File Found');
    }
    

    尝试这个:

    链接地址: http://www.djcxy.com/p/2060.html

    上一篇: 检查一个字符串是否包含JavaScript中的特定数字

    下一篇: 如何检查文件名是否包含JavaScript中的子字符串?