banner
leoking

leoking

前端开发者
tg_channel

Count the number of occurrences of a character in a string using JavaScript.

JS#

Count the number of occurrences of a character in a string in JavaScript

function countOccurrences(str, char) {
  var count = 0;
  for (var i = 0; i < str.length; i++) {
    if (str.charAt(i) === char) {
      count++;
    }
  }
  return count;
}

var string = "Hello, World!";
var character = "o";

var occurrences = countOccurrences(string, character);
console.log("Number of occurrences:", occurrences);

In this example, the countOccurrences function takes two parameters: str (the string to be checked) and char (the character to count occurrences of). Then, it uses a loop to iterate through each character in the string and increases the value of the counter variable count if the current character matches the target character. Finally, the function returns the value of the counter.

You can modify the values of string and character as needed to test with different strings and characters. The above example will print the number of occurrences of the character "o" in the string "Hello, World!".

ES6#

In ES6, you can use some new methods to count the occurrences of a character in a string. One commonly used method is to use Array.from combined with Array.reduce. Here is an example code that uses ES6 methods to count the occurrences of a character in a string:

const countOccurrences = (str, char) =>
  Array.from(str).reduce((count, currentChar) =>
    currentChar === char ? count + 1 : count, 0);

const string = "Hello, World!";
const character = "o";

const occurrences = countOccurrences(string, character);
console.log("Number of occurrences:", occurrences);

In this example, the countOccurrences function uses Array.from to convert the string into an array of characters, and then uses the Array.reduce method to iterate through the character array. By comparing the current character with the target character, we increase the value of the counter variable count. Finally, the function returns the value of the counter.

This method takes advantage of iterators and array methods in ES6, making the code more concise and elegant. In the example, we count the number of occurrences of the character "o" in the string "Hello, World!" and print the result.

Please note that using ES6 methods may require running in modern browsers or JavaScript environments that support these syntaxes.

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.