在两个单词之间获取每个字符串

时间:2014-11-15 15:48:13

标签: javascript php regex string substring

我试图为我当前的项目创建一个搜索栏。

这是当前的HTML:

<input type="text" id="searchbar"/>

CSS目前并不重要......

我可以从服务器中找到文件/文件夹:

如果您按Enter键,JavaScript会发送$ .post()

这是我的Javascript:

$.post( "files/openFolder.php",{folder : $searchtext}, function() {
})
.success(function(data) {
    if(data != "") {
        if(data.indexOf("folder:") > -1){ //contains folders..!
            foundedFolders = data;
            myfolders = foundedFolders.split(/[folder:&]/);
            myfolders = cleanArray(myfolders);
            generateFolderBoxes(myfolders);
            folderBoxSettings();
        }else if(data.indexOf("file:") > -1){ // contains files..!
            foundedFiles = data;
            myfiles = foundedFiles.split(/[file:&]/);
            myfiles = cleanArray(myfiles); //cleans the Array from empty Strings.
            generateFileBoxes(myfiles);
            fileBoxSettings();  
        }

    }
})
.fail(function() {
    alert("Sorry doesn't worked, try later again.");
});

我的问题在这里:

myfolders = foundedFolders.split(/[folder:&]/);

myfiles = foundedFiles.split(/[file:&]/);

PHP-输出:

"folder:****&file:*****&file:*****&"

我读了这个stackoverflow,以获取foldernames或文件:Get Substring between two characters using javascript

Reg-Expression输出:

["such", " - Kop", ".txt", "such", ".txt", "t", "st - Kop", ".txt", "t", "st.txt"] 

但正常情况应该是:

["suche - Kopie.txt","suche.txt","test - Kopie.txt","test.txt"]

显示它们需要这些“文件名”..

感谢您的帮助:D

1 个答案:

答案 0 :(得分:0)

您遇到的问题是分割功能中的正则表达式 具体来说,字符类包含单独字符的列表。

因此,[folder:&]确实匹配字符
中的单个字符 'f','o','l','d','e','r',':','&'

要拆分'&folder:''&'':',它应该是这样的

myfolders = foundedFolders.split(/&?folder:|[&:]+/);  

同样,适用于'&file:''&'':'

myfiles = foundedFiles.split(/&?file:|[&:]+/);