我正在开发一个应用程序,上面有小测验的问题和公式。使用一个公式,您可以将多个小测验的分数与变量相加,例如*|q1_score|* + *|q2_score|* + *|q3_score|* + *|q4_score|*。
当一个小测验问题被移动时,我想要更新字符串中在某个范围内的变量的编号。
假设小测验问题4被移到第2位,那么我想将公式字符串更新为*|q2_score|* + *|q1_score|* + *|q3_score|* + *|q4_score|*
现在我已经
const string = `*|q1_score|* + *|q2_score|* + *|q3_score|* + *|q4_score|*`;
// Update actual quiz question that was moved
const originalOrder = 4;
const newOrder = 2;
const regex = new RegExp(`\\*\\|q${originalOrder}`, "g");
let newFormula = string.replace(regex, `*|q${newOrder}_`);
// Update all quiz questions with number after newOrder
const range = '3-4';
const regex2 = new RegExp(`\\*\\|q[${range}]`, "g");
let newFormula2 = string.replace(regex2, '*|q' + parseInt(p.match(/\d+/g) + 1) + '_'); // not sure what to put as 2nd param here基本上,我想对regex \\*\\|q[2-4]检测到的字符串中的所有数字进行+1处理。
发布于 2020-06-24 11:56:38
你可以用替换
const add = (match, group) => match.replace(new RegExp(group), parseInt(group)+1)
const input = `*|q1_score|* + *|q2_score|* + *|q3_score|* + *|q4_score|*`
const result = input.replace(/q([0-9])+_score/g, add)
console.log(result);
我想更好的解决方案不是将整个状态保存在一个字符串中,而是在一个结构中(例如,一个字符串或对象数组)。
https://stackoverflow.com/questions/62554251
复制相似问题