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

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

当前回答

你可以试试这个:

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

其他回答

ES2020提供了一个新的MatchAll,它可能在这个特定的环境中使用。

这里我们创建了一个新的RegExp,请确保将“g”传递到函数中。

使用Array.from转换结果并计算长度,根据原始请求者所需的输出返回2。

let strToCheck=RegExp('is','g')let matchesReg=“这是一个字符串。”.matchAll(strToCheck)console.log(Array.from(matchesReg).length)//2

只需编码打高尔夫球丽贝卡·切尔诺夫的解决方案:-)

alert(("This is a string.".match(/is/g) || []).length);
var mystring = 'This is the lorel ipsum text';
var mycharArray = mystring.split('');
var opArr = [];
for(let i=0;i<mycharArray.length;i++){
if(mycharArray[i]=='i'){//match the character you want to match
    opArr.push(i);
  }}
console.log(opArr); // it will return matching index position
console.log(opArr.length); // it will return length

var temp=“这是一个字符串。”;console.log((temp.match(新RegExp(“is”,“g”))||[]).length);

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

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