Search code examples
javascriptphparraysregexlookbehind

PHP lookbehind in javascript


For the following string, I would like to extract the date (Monday), time (6-8pm), and Location(Location1)

Date1: Monday, 6-8pm, Location1
Date2: Tuesday, 1-3pm, Location2
Date3: Wednesday, 4-6pm, Location3

In PHP, I would do preg_match("/(?<=Date\d:\s)(.*),\s(.*),\s(.*)/", $input_line, $output_array); using lookbehind regex, and I can use $output_array to display the data separtely in an array, like:

array[0][1] = Monday, array[0][2] = 6-8pm, array[0][3] = Location1 array[1][1] = Tuesday, array[1][2] = 1-3pm, array[1][3] = Location2 array[2][1] = Wednesday, array[2][2] = 4-6pm, array[2][3] = Location3

I was just wondering how could I achieve the same thing in JavaScript?

Thanks!


Solution

  • Not sure how to do multiple matches at once with JS RegEx, but here are some non-regex solutions:

    var input = "Date1: Monday, 6-8pm, Location1\n"
              + "Date2: Tuesday, 1-3pm, Location2\n"
              + "Date3: Wednesday, 4-6pm, Location3";
    
    var input_lines = input.split("\n");
    
    var output = [];
    
    for(var iterator = 0;iterator < input_lines.length;iterator++){
        var input_line = input_lines[iterator];
    
        input_line = input_line.replace(/Date[0-9]+:\s/, '');
    
        var line_data = input_line.split(/,\s/);
    
        output.push(line_data);
    }
    

    Or, a shorter version:

    var input = "Date1: Monday, 6-8pm, Location1\n"
              + "Date2: Tuesday, 1-3pm, Location2\n"
              + "Date3: Wednesday, 4-6pm, Location3";
    
    output = [];
    
    // Just a shortened version of the loop in the previous example.
    input.split("\n").forEach(function(line){
        output.push(line.replace(/Date[0-9]+:\s/, '').split(/,\s/));
    });