admin管理员组

文章数量:1333172

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);
}

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

Share Improve this question edited Jun 27, 2019 at 9:30 Code Maniac 37.8k5 gold badges41 silver badges64 bronze badges asked Jun 27, 2019 at 9:17 oloolo 5,27115 gold badges60 silver badges96 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

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);
}

本文标签: eslintJavascript While loop condition with nocondassign errorStack Overflow