Ajouve
Ajouve

Reputation: 10089

condition and regex phonegap

I can't understand why my condition didn't works

$('#resPage').live('pageshow', function(event) {

    application.previousButton();

    //get pdf
    var text = '';
    var value;
    var get = application.readGet();
    switch(get['id']){
        case '1':
            var patt = /annales/g;
            var cutLen = 20;
            break;
         case '2':
             var patt = /copies/g;
             var cutLen = 19;
             break;
    }
    $.ajax({
        url:application.api+'/ressources',
        success:function(data){
            text = "<ul data-role='listview' data-inset='true' >"
            data = JSON.parse(data);
            for(elem in data.files){
            console.log(elem)
            console.log(patt.test(data.files[elem]));
            if(patt.test(data.files[elem])){
                console.log('add');
                value = data.files[elem].substr(1);
                text += application.textRelLink(value,cutLen);
            }
        }   
        text +="</ul>" 
        $('#resPage .content').html(text);
        $('#resPage .content ul').listview();
        }
    })
});

In my log I have:

03-02 11:03:14.722: D/CordovaLog(23226): 0
03-02 11:03:14.722: D/CordovaLog(23226): false
03-02 11:03:14.722: D/CordovaLog(23226): 1
03-02 11:03:14.722: D/CordovaLog(23226): false
03-02 11:03:14.722: D/CordovaLog(23226): 2
03-02 11:03:14.722: D/CordovaLog(23226): true
03-02 11:03:14.722: D/CordovaLog(23226): 3
03-02 11:03:14.722: D/CordovaLog(23226): true
03-02 11:03:14.730: D/CordovaLog(23226): 4
03-02 11:03:14.730: D/CordovaLog(23226): true
03-02 11:03:14.730: D/CordovaLog(23226): 5
03-02 11:03:14.745: D/CordovaLog(23226): false
03-02 11:03:14.745: D/CordovaLog(23226): 6
03-02 11:03:14.745: D/CordovaLog(23226): false

But I never have add when true

Thanks for the help

Edit:

Data value before parsing

03-02 11:25:05.253: D/CordovaLog(23611): {"files":[".\/thumbs\/pdf\/methodo\/sdsdfsd_sdf.pdf",".\/thumbs\/pdf\/methodo\/test!!.pdf",".\/thumbs\/pdf\/annales\/ddfgdfg.pdf",".\/thumbs\/pdf\/annales\/big.pdf",".\/thumbs\/pdf\/annales\/test.pdf",".\/thumbs\/pdf\/copies\/test.pdf",".\/thumbs\/pdf\/poly\/gdfhf.pdf"],"dirs":[".\/thumbs\/pdf\/poly\/",".\/thumbs\/pdf\/copies\/",".\/thumbs\/pdf\/annales\/",".\/thumbs\/pdf\/methodo\/"]}

Upvotes: 0

Views: 258

Answers (1)

MikeM
MikeM

Reputation: 13641

You need to reset the lastIndex property of the regular expression before re-testing

console.log(patt.test(data.files[elem]));
patt.lastIndex = 0;
if(patt.test(data.files[elem])){

Alternatively, if you get rid of the unnecessary g flag from the regex, there is no need to reset lastIndex.

When a regex is used with the g flag it keeps track of where the last match was found so that the next test starts searching from that point, the lastIndex.

See Why RegExp with global flag in Javascript give wrong results?.

Upvotes: 1

Related Questions