你可以使用正则表达式和match()
方法来判断字符串中某个特定字符的个数以及出现的所有位置。下面是一个示例:
function countAndFindPositions(str, char) {
var regex = new RegExp(char, 'g');
var count = str.match(regex).length;
var positions = [];
str.replace(regex, function(match, index) {
positions.push(index);
return match;
});
return {
count: count,
positions: positions
};
}
var str = 'Hello, world!';
var char = 'o';
var result = countAndFindPositions(str, char);
console.log('Count:', result.count);
console.log('Positions:', result.positions);
这段代码中的countAndFindPositions
函数接受两个参数:str
代表要处理的字符串,char
代表要查找的特定字符。它使用正则表达式创建了一个全局匹配的模式,然后使用match()
方法找到所有匹配的结果并计算个数。接着,它使用replace()
方法遍历每个匹配项,并将它们的索引位置存储在positions
数组中。最后,函数返回一个包含个数和位置数组的对象。
在上述示例中,字符串'Hello, world!'
中的字符'o'
出现了两次,分别位于索引位置4和8。因此,输出结果为:
Count: 2
Positions: [4, 8]