ghi
ghi

Reputation: 725

Strange js regexp behaviour

I've the folowing code:

$.get(TASK_FILE, function(data) {
    lines = data.split("\n");
    var place = /@[\S]*/g
    var category = /\+[\S]*/g
    lin = []
    for(line in lines)
    {
    var str = lines[line]
    var res = category.exec(str)
    console.log(res)
        if(res != null) 
    {
        str = str.replace(place, "");
        //lin[res[0]] = str;
    }

    }

    var res = category.exec("Czytanie +rosyjski @komunikacja @podrecznik")
    console.log(res)

The TASK_FILE is the url of text file which contains:

Zadania z fizyki +mFizyka @dom
Czytanie +rosyjski @komunikacja @podrecznik

As you can see I want to get the lisnes of the file that has "+something" and I want to save this something to the var but firebug output really suprise me: enter image description here

The first line of file is handeld correctly but the next is not. What am I doing wrong?

Upvotes: 1

Views: 62

Answers (1)

Martin Ender
Martin Ender

Reputation: 44259

Using the g (global) flag in combination with exec makes exec continue its search from the end of the last match. This can of course cause anomalies when you switch the search subject in the meantime. Just go with the match function on strings instead:

str.match(category);

Upvotes: 3

Related Questions