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

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

当前回答

您可以使用match来定义这样的函数:

String.prototype.count = function(search) {
    var m = this.match(new RegExp(search.toString().replace(/(?=[.\\+*?[^\]$(){}\|])/g, "\\"), "g"));
    return m ? m.length:0;
}

其他回答

您可以使用match来定义这样的函数:

String.prototype.count = function(search) {
    var m = this.match(new RegExp(search.toString().replace(/(?=[.\\+*?[^\]$(){}\|])/g, "\\"), "g"));
    return m ? m.length:0;
}

我们可以使用jssplit函数,它的长度减1就是出现的次数。

var temp = "This is a string.";
alert(temp.split('is').length-1);

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函数的翻译

Leandro Batista的答案:只是正则表达式有问题。

“使用严格”;var dataFromDB=“testal”;$('input[name=“tbInput”]').on(“change”,function(){var charToTest=$(this).val();var howManyChars=charToTest.length;var nrMatches=0;如果(howManyChars!==0){charToTest=charToTest.charAt(0);var regexp=新regexp(charToTest,'gi');var arrMatches=dataFromDB.match(正则表达式);nrMatches=arrMatches?arrMatches.length:0;}$('#result').html(nrMatches.toString());});<script src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js“></script><div class=“main”>你想数什么<input type=“text”name=“tbInput”value=“”><br/>出现次数=<span id=“result”>0</span></div>

没有人会看到这一点,但偶尔带回递归和箭头函数是很好的(双关语的意思很好)

String.prototype.occurrencesOf = function(s, i) {
 return (n => (n === -1) ? 0 : 1 + this.occurrencesOf(s, n + 1))(this.indexOf(s, (i || 0)));
};