0

Ok, really basic quetion. I'm just not getting this. I am parsing an xml feed. I am searching inside a tag for a regular expression of an image. At the minute, when I print

str.match(patt1) , I am getting:

http://www.highlandradio.com/wp-content/uploads/2013/03/jimmy.jpg,http://www.highlandradio.com/wp-content/uploads/2013/03/jimmy.jpg,jpg

in the console. I just need the first element i.e.

http://www.highlandradio.com/wp-content/uploads/2013/03/jimmy.jpg

To do this I tried str.match(patt1)[0] but this line is causing my app to crash. I am setting this varibale to equal a leftImage propert of a table row. I am also testing if it is null to 'continue' with the loop as I thought that may have been the problem.

I also tried str.match(patt1[0]) but this si not giving me the desired output either. What am I doing wrong?

EDIT: APP JS BELOW:

    var win1 = Titanium.UI.createWindow({  
    title:'Tab 1',
    backgroundColor:'#fff',
    //tabBarHidden: true

});
var tab = Titanium.UI.createTab({  
    icon:'KS_nav_views.png',
    title:'Tab 1',
    window:win1
});

var data = [];

var table = Ti.UI.createTableView({
    //data:data
});

var url="http://www.highlandradio.com/feed/"; 
//rss feed url
//var url="http://apod.nasa.gov/apod.rss"; //  rss feed url
var xhr = Titanium.Network.createHTTPClient();

xhr.onload = function() {
    // Data is returned from the blog, start parsing
    var doc = this.responseXML.documentElement;

    // begin looping through blog posts
    var items = doc.getElementsByTagName("item");
    console.log(items);
    for (var i=0;i<items.length;i++) {

        var str=items.item(i).getElementsByTagName("content:encoded").item(0).text;
        console.log("FIRST STRING TEST "+ str);
        //var src= items.item(i).getElementsByTagName("content:encoded").item(0).getAttribute("src");
        //console.log("FIRST SRC TEST "+ src);
        var patt1=/([a-z\-_0-9\/\:\.]*\.(jpg|jpeg|png|gif))/i;


        var urlMatch = str.match(patt1);
        data.push({

            title: items.item(i).getElementsByTagName("title").item(0).text,            
            leftImage: urlMatch.length > 0 ? urlMatch[0] : 'NewsStory.png',
            dataToPass: items.item(i).getElementsByTagName("description").item(0).text,
            className: "TableRow", 
            hasChild: true, 
            jsTest: true,
            js:"external.js"
        });

    }

    table.setData(data);

};

xhr.onerror = function(e) {
    // should do something more robust
    alert('Network error '+e.error);
};

xhr.open('GET',url);
xhr.send();

win1.add(table);


win1.open();
4

2 回答 2

0

您可以通过用户数组访问 match() 的函数结果,如下所示:

// Prints 1st element of str.match(patt1) to console   
console.log(str.match(patt1)[0]);

但是,如果您将来要使用匹配项,您应该将结果数组放入变量并使用它。

于 2013-07-15T13:46:01.370 回答
0

我用这条线解决了它:

`leftImage: str.match(patt1) !== null ? str.match(patt1)[0] : 'NewsStory.png',

当没有结果而不是未定义时,我忘记了匹配返回一个对象。

于 2013-07-15T15:30:28.363 回答