Search code examples
javascriptvariable-assignmentreferenceerror

ReferenceError: Invalid left-hand side in assignment while using "+="


I'm trying to solve this following kata on Codewars: Strip Comments. I think this is pretty legit code, but I'm getting the following error:

ReferenceError: Invalid left-hand side in assignment

for this part: reg += "\\" += item += "|"; (line 6)

Here is my code:

function solution(input, markers) {
  var arr = input.split("\n");
  var reg = "(";
  markers.forEach(function(item, index){
  if (!(index == markers.length)){
  reg += "\\" += item += "|";
  } else {reg += "\\" += item += ")";}
  })
  reg += ".*";
  var regex = new RegExp(reg);
  arr.forEach(function(item){
  item.replace(regex, "");
  })
  var ret = arr.toString();
  ret.replace(/\,/g, "\n");
  return ret;
};

Solution

  • += cannot be used between strings. Concatenate items using +

    function solution(input, markers) {
        var arr = input.split("\n");
        var reg = "(";
        markers.forEach(function(item, index){
        if (!(index == markers.length)){
        reg += "\\" + item + "|";
        } else {reg += "\\" + item + ")";}
        })
        reg += ".*";
        var regex = new RegExp(reg);
        arr.forEach(function(item){
        item.replace(regex, "");
        })
        var ret = arr.toString();
        ret.replace(/\,/g, "\n");
        return ret;
      };