Home >Web Front-end >JS Tutorial >Get the number of occurrences of each letter in a string through js
In the previous article "Analysis of how to reverse numbers through javascript", I introduced you to the method of reversing numbers in javascript. This article continues to bring you the basic use of javascript. I hope it will be useful to you. It will help!
As the title states, the central question of this article is "Write a JavaScript function to get the number of occurrences of each letter in a specified string".
I will give you the code directly below:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <script> function Char_Counts(str1) { var uchars = {}; str1.replace(/\S/g, function(l){uchars[l] = (isNaN(uchars[l]) ? 1 : uchars[l] + 1);}); return uchars; } console.log(Char_Counts("The quick brown fox jumps over the lazy dog")); </script> </body> </html>
The obtained results are as follows:
Then it can be clear from the above picture How many times do you see each letter appearing?
Here is a summary of 2 methods used:
1, replace()
method is used to replace some characters with other characters in a string, or Replace a substring that matches the regular expression;
The syntax is "stringObject.replace(regexp/substr,replacement)
"; return value: a new string, using replacement replaces the first match or all subsequent matches of regexp. The
parameters respectively represent:
regexp/substr,规定子字符串或要替换的模式的 RegExp 对象。请注意,如果该值是一个字符串,则将它作为要检索的直接量文本模式,而不是首先被转换为 RegExp 对象。 replacement,一个字符串值。规定了替换文本或生成替换文本的函数。
2, isNaN()
The function is used to check whether its parameters are non-numeric values.
The syntax is "isNaN(x)
", the parameter x represents the value to be detected; return value: if x is a special non-numeric value NaN (or can be converted to such value), the returned value is true. If x is any other value, returns false.
Note: The isNaN() function is usually used to detect the results of parseFloat() and parseInt() to determine whether they represent legal numbers. Of course, you can also use the isNaN() function to detect arithmetic errors, such as using 0 as a divisor.
Finally, I would like to recommend "JavaScript Basics Tutorial" ~ Welcome everyone to learn ~
The above is the detailed content of Get the number of occurrences of each letter in a string through js. For more information, please follow other related articles on the PHP Chinese website!