Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

การนับจำนวนครั้งที่สตริงเฉพาะปรากฏในสตริงด้วย JavaScript

เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่รับสตริงสองตัว คือ str1 และ str2 ฟังก์ชันควรนับและคืนจำนวนครั้งที่ str2 ปรากฏใน str1

ตัวอย่าง:

count('this is a string', 'is') should return 2;

ตัวอย่างโค้ด

const str1 = 'this is a string';
const str2 = 'is';
const countOccurrences = (str1, str2, allowOverlapping = true) => {
  str1 += "";
  str2 += "";
  if (str2.length <= 0) return (str1.length + 1);
  var n = 0,
  pos = 0,
  step = allowOverlapping ? 1 : str2.length;
  while (true) {
    pos = str1.indexOf(str2, pos);
    if (pos >= 0) {
      ++n;
      pos += step;
    } else break;
  }
  return n;
};
console.log(countOccurrences(str1, str2));

ผลลัพธ์

ผลลัพธ์ที่แสดงในคอนโซลจะเป็นดังนี้:

2