JavaScript。计算给定字符串中符号的数量

JavaScript. Count the number of symbols in the given string

您如何仅使用字符串方法、数组方法和循环来解决这个挑战?

Count the number of 'xx' in the given string. We'll say that overlapping is allowed, so 'xxx' contains 2 'xx'.

Examples:

countXX('abcxx') → 1
countXX('xxx') → 2
countXX('xxxx') → 3

谢谢!

countX('abcxx') - 1

这将适用于正式字符串,除非它们包含单个 x.

const input = 'abcxxx';
const asArray = Array.from(input);    // get ["a", "b", "c", "x", "x", "x"]

// Make 2 arrays
const array1 = asArray.slice(1);      // get ["b", "c", "x", "x", "x"]
const array2 = asArray.slice(0, -1);  // get ["a", "b", "c", "x", "x"]

// Combine arrays to get array of pairs
const pairsArray = new Array();
for (let i = 0; i < array1.length && i < array2.length; i++) {
    pairsArray.push(array1[i] + array2[i]);
}

// Now pairsArray is: ["ab", "bc", "cx", "xx", "xx"]

// Count "xx" in pairs array
const answer = pairsArray.filter(pair => pair === "xx").length;

console.log(answer);