如何计算特定字符串在另一个字符串中出现的次数。例如,这就是我试图在Javascript中做的事情:

var temp = "This is a string.";
alert(temp.count("is")); //should output '2'

当前回答


subst_count从php转换为Javascript


Locutus(将Php翻译为JS的包)subst_count(官方页面,代码复制如下)

function substr_count (haystack, needle, offset, length) { 
  // eslint-disable-line camelcase
  //  discuss at: https://locutus.io/php/substr_count/
  // original by: Kevin van Zonneveld (https://kvz.io)
  // bugfixed by: Onno Marsman (https://twitter.com/onnomarsman)
  // improved by: Brett Zamir (https://brett-zamir.me)
  // improved by: Thomas
  //   example 1: substr_count('Kevin van Zonneveld', 'e')
  //   returns 1: 3
  //   example 2: substr_count('Kevin van Zonneveld', 'K', 1)
  //   returns 2: 0
  //   example 3: substr_count('Kevin van Zonneveld', 'Z', 0, 10)
  //   returns 3: false

  var cnt = 0

  haystack += ''
  needle += ''
  if (isNaN(offset)) {
    offset = 0
  }
  if (isNaN(length)) {
    length = 0
  }
  if (needle.length === 0) {
    return false
  }
  offset--

  while ((offset = haystack.indexOf(needle, offset + 1)) !== -1) {
    if (length > 0 && (offset + needle.length) > length) {
      return false
    }
    cnt++
  }

  return cnt
}

查看Locutus对Php的subst_count函数的翻译

其他回答

正则表达式(global的缩写)中的g表示搜索整个字符串,而不仅仅是查找第一个出现的字符串。此匹配是两次:

var temp=“这是一个字符串。”;var count=(temp.match(/is/g)| |[]).length;console.log(计数);

如果没有匹配项,则返回0:

var temp=“Hello World!”;var count=(temp.match(/is/g)| |[]).length;console.log(计数);

试试看

<?php 
$str = "33,33,56,89,56,56";
echo substr_count($str, '56');
?>

<script type="text/javascript">
var temp = "33,33,56,89,56,56";
var count = temp.match(/56/g);  
alert(count.length);
</script>

第二次迭代次数较少(仅当子字符串的第一个字母匹配时),但循环仍使用2:

   function findSubstringOccurrences(str, word) {
        let occurrences = 0;
        for(let i=0; i<str.length; i++){
            if(word[0] === str[i]){ // to make it faster and iterate less
                for(let j=0; j<word.length; j++){
                    if(str[i+j] !== word[j]) break;
                    if(j === word.length - 1) occurrences++;
                }
            }
        }
        return occurrences;
    }
    
    console.log(findSubstringOccurrences("jdlfkfomgkdjfomglo", "omg"));

你可以试试这个:

var theString=“这是一个字符串。”;console.log(String.split(“is”).length-1);

无正则表达式的简单版本:

var temp=“这是一个字符串。”;var计数=(临时拆分('is').长度-1);警报(计数);