统计某一字符或字符串在另一个字符串中出现的次数
There are several ways to count the occurrences of a character or substring within a string in JavaScript (frontend development):
1. Using split()
and length
(for simple characters or substrings that don't overlap):
This is the simplest approach for characters or non-overlapping substrings. It splits the string into an array using the target character/substring as a delimiter. The resulting array's length minus one gives the number of occurrences.
function countOccurrences(str, target) {
if (target === "") {
return str.length + 1; // Handle empty target string case
}
return str.split(target).length - 1;
}
const string = "This is a test string.";
const char = "s";
const substring = "is";
console.log(`Occurrences of '${char}':`, countOccurrences(string, char)); // Outputs: 3
console.log(`Occurrences of '${substring}':`, countOccurrences(string, substring)); // Outputs: 2
2. Using a for
loop and indexOf()
(handles overlapping substrings):
This method iteratively searches for the target substring using indexOf()
, starting from the last found index. It correctly counts overlapping occurrences.
function countOccurrences(str, target) {
let count = 0;
let index = str.indexOf(target);
while (index !== -1) {
count++;
index = str.indexOf(target, index + 1); // Start next search from after current occurrence
}
return count;
}
const string = "abababa";
const substring = "aba";
console.log(`Occurrences of '${substring}':`, countOccurrences(string, substring)); // Outputs: 2 (correctly handles overlap)
3. Using a regular expression (flexible, but can be more complex):
Regular expressions offer powerful pattern matching. The g
flag (global) is crucial for finding all occurrences.
function countOccurrences(str, target) {
const regex = new RegExp(target, 'g'); // 'g' flag for all occurrences
const matches = str.match(regex);
return matches ? matches.length : 0; // Handle case where no matches are found
}
const string = "This is a test string.";
const char = "s";
const substring = "is";
console.log(`Occurrences of '${char}':`, countOccurrences(string, char)); // Outputs: 3
console.log(`Occurrences of '${substring}':`, countOccurrences(string, substring)); // Outputs: 2
Which method to use?
- For simple characters or non-overlapping substrings,
split()
is often the easiest and most efficient. - For overlapping substrings, the
for
loop withindexOf()
is a good choice. - Regular expressions are the most flexible but can be more complex to set up, especially if the target string contains special characters that need escaping. They are particularly useful for more complex pattern matching scenarios.
Remember to handle edge cases, such as empty target strings or when the target is not found, as shown in the examples. Choose the method that best suits your specific needs and complexity of the task.