10 Helpful JavaScript Code Snippets v3
10 Helpful JavaScript Code Snippets v3
Write a function that converts a string to title case (i.e., capitalizes the first
letter of each word) in JavaScript. 2
Write a function that calculates the sum of all digits in a given integer in
JavaScript. 2
return
num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
Explanation: The function first converts the input number to a
string using the toString() method. Then, it uses a regular
expression (/\B(?=(\d{3})+(?!\d))/g) to match any digits that
are not preceded by the beginning of a number (\B) and are
followed by groups of three digits ((\d{3})+) that are not
followed by more digits ((?!\d)). The replace() method then
replaces each match with a comma.
}
Explanation: The function uses the slice() method with a negative
index to return the last n elements of the input array.