I have this regex which checks if the password has one digit at least.
^(?=.*[0-9]).{6,}$
How do I modify the regex to check if the sum of all the digits in the password is equal to say 10. So this string should match "dhbqdw46". This shouldn't "jwhf1ejhjh0".
Regular expressions are designed for pattern matching and cannot perform arithmetic operations like calculating the sum of digits.
As mentioned in the comments, you'll need to implement the logic yourself. Since you've tagged this question with JavaScript, here's a solution using JavaScript:
function isValidPassword(password, targetSum){
const digits = password.match(/\d/g) || [];
const sum = digits.reduce((sum, digit) => sum + parseInt(digit, 10), 0);
return sum === targetSum
}
const password1 = "dhbqdw46";
const password2 = "jwhf1ejhjh0";
console.log(isValidPassword(password1, 10)); // Output: true
console.log(isValidPassword(password2, 10)); // Output: false