Question:
[I need to be able to count how many e.g. 1, or 2, or 3 there are in a word e.g. “12121”]
Product:
[ e.g. Wix Editor]
What are you trying to achieve:
[I have looked at several codes but I don’t see any that meet this, I hope you can help, Thanks]
What have you already tried:
[Share resources, forum topics, articles, or tutorials you’ve already used to try and answer your question.]
Additional information:
[Include any other pertinent details or information that might be helpful for people to know when trying to answer your question.]
You probably want a function like this, where str is the string you want to count how many occurrences of a number are in it, e.g. “12121”, and digit being the number you want to count occurrences of
function countDigitOccurrences(str, digit) {
let target = String(digit);
let count = 0;
for (let char of str) {
if (char === target) {
count++;
}
}
return count;
}
Thanks, that code works.
I had also found a code that also works, but I can’t figure out how to use a variable, then it won’t work.
function countDigits (text,tegn) {
console.log("tegn: = "+tegn);
// Replace ‘1’, ‘2’, and ‘3’ with the digits you want to count
//let count = (text.match(/[1]/g) || ).length;
let count = (text.match(/[tegn]/g) || ).length;
return count;
}
I don’t understand what these codes in brackets stand for, I’ve tried looking them up, but can’t find any explanation for them. Maybe you can give me a hint. Thanks in advance.
I don’t know any other language than Danish, so what I write I translate via google. Via AI, I received information on how I could use variables in the program, which I also insert so that others can also benefit from it.
I am grateful for your help as I am not as sharp as before, but I can still program well. Thanks.
let text = “123451”;
let digit = “1”; // Variablen du vil tælle
let count = (text.match(new RegExp (digit, “g”)) || ).length;
console.log(count); // Output: 2