Javascript
 Computer >> コンピューター >  >> プログラミング >> Javascript

JavaScriptの文字列内の特定の文字列の出現をカウントする方法


str1とstr2の2つの文字列を受け取るJavaScript関数を作成する必要があります。次に、関数は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

  1. JavaScriptオブジェクトのコンテンツを文字列形式で表示するにはどうすればよいですか?

    document.getElementById()を使用し、innerHTMLを使用して表示します。以下はコードです- 例 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initialscale=1.0"> <title>Document</title>

  2. ドキュメント全体のHTMLをJavaScriptで文字列として取得するにはどうすればよいですか?

    ドキュメントのHTML全体を文字列として取得するには、-のようなinnerHTMLの概念を使用します。 document.documentElement.innerHTML; 例 以下はコードです- <!DOCTYPE html> <html lang="en"> <head>    <meta charset="UTF-8">    <meta name="viewport" content="width=device-widt