how to limit characters in a string text in javascript code example
Example 1: javascript max characters string function
const getMaxLetter = (str) => {
let max = 0;
let maxChar = '';
str.split('').forEach((char) => {
if (str.split(char).length > max) {
max = str.split(char).length - 1;
maxChar = char;
}
});
return `The max letter is : ${maxChar} and the max number of times it is seen is: ${max} times`;
};
Example 2: max char js
function maxChar(str) {
let charCountObj = {};
let maxChar = "";
let maxCount = 0;
for (let i = 0; i < str.length; i++) {
const char = str[i];
charCountObj[char] = charCountObj[char] + 1 || 1;
if (charCountObj[char] > maxCount) {
maxChar = char;
maxCount = charCountObj[char];
}
}
return maxChar;
}