Javascript While loop condition with no-cond-assign error

Viewed 1996

Error: Expected a conditional expression and instead saw an assignment. (no-cond-assign)

const re = /<%([^%>]+)?%>/g;
let match;
while (match = re.exec('<%hello%> you <%!%>')) {
  console.log(match);
}

Doing a while loop to reassign match, but getting no-cond-assign error. I can still get output without errors but what is the best way to correct the syntax? Thanks

2 Answers

One option is to use a do-while loop instead, so you can break inside a while(true):

const re = /<%([^%>]+)?%>/g;
while (true) {
  const match = re.exec('<%hello%> you <%!%>');
  if (!match) {
    break;
  }
  console.log(match);
}

IMO, this situation is the one time in Javascript where assignment inside a conditional (in your original code) is clearer than the alternative. I wouldn't be afraid of disabling that linting rule for this one line.

Assuming you want to retrieve the first capturing group, you'll be able to use string.prototype.matchAll in modern environments:

const str = '<%hello%> you <%!%>';
const contentInsidePercents = [...str.matchAll(/<%([^%>]+)?%>/g)]
  .map(match => match[1]);
console.log(contentInsidePercents);

You can simply use

while ((match = re.exec('<%hello%> you <%!%>'))!== null)

const re = /<%([^%>]+)?%>/g;
let match;
while ((match = re.exec('<%hello%> you <%!%>'))!== null) {
  console.log(match);
}

Related