简体   繁体   English

如何统计字符串在字符串中的出现次数?

[英]How to count string occurrence in string?

How can I count the number of times a particular string occurs in another string.如何计算特定字符串在另一个字符串中出现的次数。 For example, this is what I am trying to do in Javascript:例如,这就是我在 Javascript 中尝试做的事情:

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

The g in the regular expression (short for global ) says to search the whole string rather than just find the first occurrence.正则表达式( global 的缩写)中的g表示要搜索整个字符串,而不是只找到第一次出现。 This matches is twice:这场比赛is两次:

 var temp = "This is a string."; var count = (temp.match(/is/g) || []).length; console.log(count);

And, if there are no matches, it returns 0 :并且,如果没有匹配项,则返回0

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

/** Function that count occurrences of a substring in a string;
 * @param {String} string               The string
 * @param {String} subString            The sub string to search for
 * @param {Boolean} [allowOverlapping]  Optional. (Default:false)
 *
 * @author Vitim.us https://gist.github.com/victornpb/7736865
 * @see Unit Test https://jsfiddle.net/Victornpb/5axuh96u/
 * @see http://stackoverflow.com/questions/4009756/how-to-count-string-occurrence-in-string/7924240#7924240
 */
function occurrences(string, subString, allowOverlapping) {

    string += "";
    subString += "";
    if (subString.length <= 0) return (string.length + 1);

    var n = 0,
        pos = 0,
        step = allowOverlapping ? 1 : subString.length;

    while (true) {
        pos = string.indexOf(subString, pos);
        if (pos >= 0) {
            ++n;
            pos += step;
        } else break;
    }
    return n;
}

Usage用法

occurrences("foofoofoo", "bar"); //0

occurrences("foofoofoo", "foo"); //3

occurrences("foofoofoo", "foofoo"); //1

allowOverlapping允许重叠

occurrences("foofoofoo", "foofoo", true); //2

Matches:火柴:

  foofoofoo
1 `----´
2    `----´

Unit Test单元测试

Benchmark基准

I've made a benchmark test and my function is more then 10 times faster then the regexp match function posted by gumbo.我做了一个基准测试,我的函数比 gumbo 发布的正则表达式匹配函数快 10 倍以上。 In my test string is 25 chars length.在我的测试字符串中,长度为 25 个字符。 with 2 occurences of the character 'o'.字符 'o' 出现 2 次。 I executed 1 000 000 times in Safari.我在 Safari 中执行了 1 000 000 次。

Safari 5.1 Safari 5.1

Benchmark> Total time execution: 5617 ms (regexp) Benchmark> 总执行时间:5617 ms (regexp)

Benchmark> Total time execution: 881 ms (my function 6.4x faster)基准> 总执行时间:881 毫秒(我的函数快 6.4 倍)

Firefox 4火狐 4

Benchmark> Total time execution: 8547 ms (Rexexp) Benchmark> 总执行时间:8547 ms (Rexexp)

Benchmark> Total time execution: 634 ms (my function 13.5x faster)基准> 总执行时间:634 毫秒(我的函数快了 13.5 倍)


Edit: changes I've made编辑:我所做的更改

  • cached substring length缓存子串长度

  • added type-casting to string.向字符串添加了类型转换。

  • added optional 'allowOverlapping' parameter添加了可选的“allowOverlapping”参数

  • fixed correct output for "" empty substring case.修复了 "" 空子字符串情况的正确输出。

Gist 要旨
function countInstances(string, word) {
   return string.split(word).length - 1;
}

You can try this:你可以试试这个:

 var theString = "This is a string."; console.log(theString.split("is").length - 1);

My solution:我的解决方案:

 var temp = "This is a string."; function countOcurrences(str, value) { var regExp = new RegExp(value, "gi"); return (str.match(regExp) || []).length; } console.log(countOcurrences(temp, 'is'));

You can use match to define such function:您可以使用match来定义这样的函数:

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

The non-regex version:非正则表达式版本:

 var string = 'This is a string', searchFor = 'is', count = 0, pos = string.indexOf(searchFor); while (pos > -1) { ++count; pos = string.indexOf(searchFor, ++pos); } console.log(count); // 2

只是打高尔夫球Rebecca Chernoff解决方案:-)

alert(("This is a string.".match(/is/g) || []).length);

 String.prototype.Count = function (find) { return this.split(find).length - 1; } console.log("This is a string.".Count("is"));

This will return 2.这将返回 2。

Here is the fastest function!这里是最快的功能!

Why is it faster?为什么它更快?

  • Doesn't check char by char (with 1 exception)不按字符检查字符(有 1 个例外)
  • Uses a while and increments 1 var (the char count var) vs. a for loop checking the length and incrementing 2 vars (usually var i and a var with the char count)使用一段时间并增加 1 个变量(字符计数变量)与检查长度并增加 2 个变量的 for 循环(通常是变量 i 和带有字符计数的变量)
  • Uses WAY less vars使用更少的变量
  • Doesn't use regex!不使用正则表达式!
  • Uses an (hopefully) highly optimized function使用(希望)高度优化的功能
  • All operations are as combined as they can be, avoiding slowdowns due to multiple operations所有操作尽可能组合在一起,避免因多次操作而导致速度减慢

    String.prototype.timesCharExist=function(c){var t=0,l=0,c=(c+'')[0];while(l=this.indexOf(c,l)+1)++t;return t};

Here is a slower and more readable version:这是一个更慢且更易读的版本:

    String.prototype.timesCharExist = function ( chr ) {
        var total = 0, last_location = 0, single_char = ( chr + '' )[0];
        while( last_location = this.indexOf( single_char, last_location ) + 1 )
        {
            total = total + 1;
        }
        return total;
    };

This one is slower because of the counter, long var names and misuse of 1 var.由于计数器、长 var 名称和滥用 1 var,这个速度较慢。

To use it, you simply do this:要使用它,您只需执行以下操作:

    'The char "a" only shows up twice'.timesCharExist('a');

Edit: (2013/12/16)编辑:(2013/12/16)

DON'T use with Opera 12.16 or older!不要与 Opera 12.16 或更高版本一起使用! it will take almost 2.5x more than the regex solution!它将比正则表达式解决方案多花近 2.5 倍的时间!

On chrome, this solution will take between 14ms and 20ms for 1,000,000 characters.在 chrome 上,对于 1,000,000 个字符,此解决方案将花费 14 到 20 毫秒。

The regex solution takes 11-14ms for the same amount.对于相同的数量,正则表达式解决方案需要 11-14 毫秒。

Using a function (outside String.prototype ) will take about 10-13ms.使用函数(在String.prototype之外)大约需要 10-13 毫秒。

Here is the code used:这是使用的代码:

    String.prototype.timesCharExist=function(c){var t=0,l=0,c=(c+'')[0];while(l=this.indexOf(c,l)+1)++t;return t};

    var x=Array(100001).join('1234567890');

    console.time('proto');x.timesCharExist('1');console.timeEnd('proto');

    console.time('regex');x.match(/1/g).length;console.timeEnd('regex');

    var timesCharExist=function(x,c){var t=0,l=0,c=(c+'')[0];while(l=x.indexOf(c,l)+1)++t;return t;};

    console.time('func');timesCharExist(x,'1');console.timeEnd('func');

The result of all the solutions should be 100,000!所有解的结果应该是100,000!

Note: if you want this function to count more than 1 char, change where is c=(c+'')[0] into c=c+''注意:如果您希望此函数计算超过 1 个字符,请将 where is c=(c+'')[0]更改为c=c+''

 var temp = "This is a string."; console.log((temp.match(new RegExp("is", "g")) || []).length);

I think the purpose for regex is much different from indexOf .我认为 regex 的目的与indexOf大不相同。 indexOf simply find the occurance of a certain string while in regex you can use wildcards like [AZ] which means it will find any capital character in the word without stating the actual character. indexOf只是查找某个字符串的出现,而在正则表达式中,您可以使用[AZ]类的通配符,这意味着它将在单词中查找任何大写字符,而无需说明实际字符。

Example:例子:

 var index = "This is a string".indexOf("is"); console.log(index); var length = "This is a string".match(/[az]/g).length; // where [az] is a regex wildcard expression thats why its slower console.log(length);

Super duper old, but I needed to do something like this today and only thought to check SO afterwards.超级老,但我今天需要做这样的事情,后来才想检查一下。 Works pretty fast for me.对我来说工作得很快。

String.prototype.count = function(substr,start,overlap) {
    overlap = overlap || false;
    start = start || 0;

    var count = 0, 
        offset = overlap ? 1 : substr.length;

    while((start = this.indexOf(substr, start) + offset) !== (offset - 1))
        ++count;
    return count;
};
       var myString = "This is a string.";
        var foundAtPosition = 0;
        var Count = 0;
        while (foundAtPosition != -1)
        {
            foundAtPosition = myString.indexOf("is",foundAtPosition);
            if (foundAtPosition != -1)
            {
                Count++;
                foundAtPosition++;
            }
        }
        document.write("There are " + Count + " occurrences of the word IS");

Refer :- count a substring appears in the string for step by step explanation.请参阅:-计算字符串中出现的子字符串以获取分步说明。

For anyone that finds this thread in the future, note that the accepted answer will not always return the correct value if you generalize it, since it will choke on regex operators like $ and .对于将来发现此线程的任何人,请注意,如果您对其进行概括,则接受的答案将不会总是返回正确的值,因为它会阻塞$和 等正则表达式运算符. . . Here's a better version, that can handle any needle:这是一个更好的版本,可以处理任何针:

function occurrences (haystack, needle) {
  var _needle = needle
    .replace(/\[/g, '\\[')
    .replace(/\]/g, '\\]')
  return (
    haystack.match(new RegExp('[' + _needle + ']', 'g')) || []
  ).length
}

Building upon @Vittim.us answer above.建立在@Vittim.us 上面的回答之上。 I like the control his method gives me, making it easy to extend, but I needed to add case insensitivity and limit matches to whole words with support for punctuation.我喜欢他的方法给我的控制,使其易于扩展,但我需要添加不区分大小写和限制匹配整个单词并支持标点符号。 (eg "bath" is in "take a bath." but not "bathing") (例如,“洗澡”在“洗澡”中。而不是“洗澡”)

The punctuation regex came from: https://stackoverflow.com/a/25575009/497745 ( How can I strip all punctuation from a string in JavaScript using regex? )标点正则表达式来自: https : //stackoverflow.com/a/25575009/497745如何使用正则表达式从 JavaScript 中的字符串中删除所有标点?

function keywordOccurrences(string, subString, allowOverlapping, caseInsensitive, wholeWord)
{

    string += "";
    subString += "";
    if (subString.length <= 0) return (string.length + 1); //deal with empty strings

    if(caseInsensitive)
    {            
        string = string.toLowerCase();
        subString = subString.toLowerCase();
    }

    var n = 0,
        pos = 0,
        step = allowOverlapping ? 1 : subString.length,
        stringLength = string.length,
        subStringLength = subString.length;

    while (true)
    {
        pos = string.indexOf(subString, pos);
        if (pos >= 0)
        {
            var matchPos = pos;
            pos += step; //slide forward the position pointer no matter what

            if(wholeWord) //only whole word matches are desired
            {
                if(matchPos > 0) //if the string is not at the very beginning we need to check if the previous character is whitespace
                {                        
                    if(!/[\s\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&\(\)*+,\-.\/:;<=>?@\[\]^_`{|}~]/.test(string[matchPos - 1])) //ignore punctuation
                    {
                        continue; //then this is not a match
                    }
                }

                var matchEnd = matchPos + subStringLength;
                if(matchEnd < stringLength - 1)
                {                        
                    if (!/[\s\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&\(\)*+,\-.\/:;<=>?@\[\]^_`{|}~]/.test(string[matchEnd])) //ignore punctuation
                    {
                        continue; //then this is not a match
                    }
                }
            }

            ++n;                
        } else break;
    }
    return n;
}

Please feel free to modify and refactor this answer if you spot bugs or improvements.如果您发现错误或改进,请随时修改和重构此答案。

 function get_occurrence(varS,string){//Find All Occurrences c=(string.split(varS).length - 1); return c; } temp="This is a string."; console.log("Total Occurrence is "+get_occurrence("is",temp)); 

Use get_occurrence(varS,string) to find occurrence of both characters and string in a String. 使用get_occurrence(varS,string)查找字符串中字符和字符串的出现。

Try it尝试一下

<?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>

Simple version without regex:没有正则表达式的简单版本:

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

No one will ever see this, but it's good to bring back recursion and arrow functions once in a while (pun gloriously intended)没有人会看到这一点,但偶尔带回递归和箭头函数是件好事(双关语意为光荣)

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

Now this is a very old thread i've come across but as many have pushed their answer's, here is mine in a hope to help someone with this simple code.现在这是我遇到的一个非常古老的线程,但由于许多人已经提出了他们的答案,这里是我的,希望能通过这个简单的代码帮助某人。

 var search_value = "This is a dummy sentence!"; var letter = 'a'; /*Can take any letter, have put in a var if anyone wants to use this variable dynamically*/ letter = letter && "string" === typeof letter ? letter : ""; var count; for (var i = count = 0; i < search_value.length; count += (search_value[i++] == letter)); console.log(count);

I'm not sure if it is the fastest solution but i preferred it for simplicity and for not using regex (i just don't like using them!)我不确定它是否是最快的解决方案,但为了简单和不使用正则表达式,我更喜欢它(我只是不喜欢使用它们!)

 function substrCount( str, x ) {
   let count = -1, pos = 0;
   do {
     pos = str.indexOf( x, pos ) + 1;
     count++;
   } while( pos > 0 );
   return count;
 }

ES2020 offers a new MatchAll which might be of use in this particular context. ES2020 提供了一个新的 MatchAll,它可能在这个特定的上下文中有用。

Here we create a new RegExp, please ensure you pass 'g' into the function.这里我们创建了一个新的 RegExp,请确保将 'g' 传递给函数。

Convert the result using Array.from and count the length, which returns 2 as per the original requestor's desired output.使用 Array.from 转换结果并计算长度,根据原始请求者的期望输出返回 2。

 let strToCheck = RegExp('is', 'g') let matchesReg = "This is a string.".matchAll(strToCheck) console.log(Array.from(matchesReg).length) // 2

A simple way would be to split the string on the required word, the word for which we want to calculate the number of occurences, and subtract 1 from the number of parts:一种简单的方法是将字符串拆分为所需单词,即我们要计算出现次数的单词,然后从部分数中减去 1:

function checkOccurences(string, word) {
      return string.split(word).length - 1;
}
const text="Let us see. see above, see below, see forward, see backward, see left, see right until we will be right"; 
const count=countOccurences(text,"see "); // 2

We can use the js split function, and it's length minus 1 will be the number of occurrences.我们可以用js split function,它的长度减1就是出现的次数。

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

Here is my solution.这是我的解决方案。 I hope it would help someone我希望它能帮助别人

const countOccurence = (string, char) => {
const chars = string.match(new RegExp(char, 'g')).length
return chars;
}

 var countInstances = function(body, target) { var globalcounter = 0; var concatstring = ''; for(var i=0,j=target.length;i<body.length;i++){ concatstring = body.substring(i-1,j); if(concatstring === target){ globalcounter += 1; concatstring = ''; } } return globalcounter; }; console.log( countInstances('abcabc', 'abc') ); // ==> 2 console.log( countInstances('ababa', 'aba') ); // ==> 2 console.log( countInstances('aaabbb', 'ab') ); // ==> 1

A little late but, assuming we have the following string: 有点晚了,但是假设我们有以下字符串:

var temp = "This is a string.";

First we split on whatever you are looking to match, this will return an array of strings. 首先,我们根据您要匹配的内容进行拆分,这将返回一个字符串数组。

var array = temp.split("is");

Then we get the length of it and subtract 1 to it since split defaults to an array of size 1 and by consequence increments its size every-time it finds an occurrence. 然后我们得到它的长度并减去1,因为split默认为大小为1的数组,因此每次发现一个出现时都会增加其大小。

var occurrenceCount = array.length - 1;
alert(occurrenceCount); //should output '2'

You can also do all this in one line as follows: 您还可以在一行中完成所有这些操作,如下所示:

alert("This is a string.".split("is").length - 1); //should output '2'

Hope it helps :D 希望对您有帮助:D

This solution is based on the .replace() method that accept a RegEx as first parameter and a function as second parameter that we can use as a closure to increment a counter... 此解决方案基于.replace()方法,该方法接受RegEx作为第一个参数,并接受函数作为第二个参数 ,我们可以将其用作闭合以增加计数器...

/**
 * Return the frequency of a substring in a string
 * @param {string} string - The string.
 * @param {string} string - The substring to count.
 * @returns {number} number - The frequency.
 * 
 * @author Drozerah https://gist.github.com/Drozerah/2b8e08d28413d66c3e63d7fce80994ce
 * @see https://stackoverflow.com/a/55670859/9370788
 */
const subStringCounter = (string, subString) => {

    let count = 0
    string.replace(new RegExp(subString, 'gi'), () => count++)
    return count
}

Usage 用法

subStringCounter("foofoofoo", "bar"); //0

subStringCounter("foofoofoo", "foo"); //3

came across this post. 遇到了这个职位。

let str = 'As sly as a fox, as strong as an ox';

let target = 'as'; // let's look for it

let pos = 0;
while (true) {
  let foundPos = str.indexOf(target, pos);
  if (foundPos == -1) break;

  alert( `Found at ${foundPos}` );
  pos = foundPos + 1; // continue the search from the next position
}

The same algorithm can be layed out shorter: 可以将相同的算法布置得更短:

let str = "As sly as a fox, as strong as an ox";
let target = "as";

let pos = -1;
while ((pos = str.indexOf(target, pos + 1)) != -1) {
  alert( pos );
}

substr_count translated to Javascript from php substr_count从 php 转换为 Javascript


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
}

Check out Locutus's Translation Of Php's substr_count function查看 Locutus 对 Php 的 substr_count 函数的翻译

你可以试试这个

let count = s.length - s.replace(/is/g, "").length;

The parameters: ustring: the superset string countChar: the substring参数: ustring:超集字符串 countChar:子字符串

A function to count substring occurrence in JavaScript:在 JavaScript 中计算子字符串出现次数的函数:

 function subStringCount(ustring, countChar){ var correspCount = 0; var corresp = false; var amount = 0; var prevChar = null; for(var i=0; i!=ustring.length; i++){ if(ustring.charAt(i) == countChar.charAt(0) && corresp == false){ corresp = true; correspCount += 1; if(correspCount == countChar.length){ amount+=1; corresp = false; correspCount = 0; } prevChar = 1; } else if(ustring.charAt(i) == countChar.charAt(prevChar) && corresp == true){ correspCount += 1; if(correspCount == countChar.length){ amount+=1; corresp = false; correspCount = 0; prevChar = null; }else{ prevChar += 1 ; } }else{ corresp = false; correspCount = 0; } } return amount; } console.log(subStringCount('Hello World, Hello World', 'll'));

 var str = 'stackoverflow'; var arr = Array.from(str); console.log(arr); for (let a = 0; a <= arr.length; a++) { var temp = arr[a]; var c = 0; for (let b = 0; b <= arr.length; b++) { if (temp === arr[b]) { c++; } } console.log(`the ${arr[a]} is counted for ${c}`) }

Iterate less the second time (just when first letter of substring matches) but still uses 2 for loops:第二次迭代较少(仅当子字符串的第一个字母匹配时)但仍然使用 2 for 循环:

   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"));
//Try this code

const countSubStr = (str, search) => {
    let arrStr = str.split('');
    let i = 0, count = 0;

    while(i < arrStr.length){
        let subStr = i + search.length + 1 <= arrStr.length ?
                  arrStr.slice(i, i+search.length).join('') :
                  arrStr.slice(i).join('');
        if(subStr === search){
            count++;
            arrStr.splice(i, search.length);
        }else{
            i++;
        }
    }
    return count;
  }
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
const getLetterMatchCount = (guessedWord, secretWord) => {
  const secretLetters = secretWord.split('');
  const guessedLetterSet = new Set(guessedWord);
  return secretLetters.filter(letter => guessedLetterSet.has(letter)).length;
};
const str = "rahul";
const str1 = "rajendra";

getLetterMatchCount(str, str1)
function substringFrequency(string , substring){
    let index = string.indexOf(substring)
    let occurenceFrequency  = 0
    for (let i=0 ; i < string.length  ; i++){
        if (index != -1){
            occurenceFrequency ++
            index = string.indexOf(substring , index+1)
        }else{
            break
        } 
       }
    return (occurenceFrequency)
}

Here is my solution, in 2022, using map() and filter():这是我在 2022 年使用 map() 和 filter() 的解决方案:

string = "Xanthous: A person with yellow hair. Her hair was very xanthous in colour."       
count = string.split('').map((e,i) => { if(e === 'e') return i;}).filter(Boolean).length

Just for the fun of using these functions.只是为了使用这些功能的乐趣。 The example counts the number of "e" in my string.该示例计算了我的字符串中“e”的数量。

This is the same as using the match() function:这与使用 match() function 相同:

(string.match(/e/g)||[]).length

or simply the split() function:或者只是 split() function:

string.split('e').length - 1

I think the best is to use match(), because it consumes less resources!我认为最好的是使用match(),因为它消耗的资源更少! My answer is just for fun and to show that there are many possibilities to solve this problem我的回答只是为了好玩,并表明解决这个问题有很多可能性

added this optimization:添加了此优化:

How to count string occurrence in string? 如何统计字符串在字符串中的出现次数?

This is probably the fastest implementation here, but it would be even faster if you replaced "++pos" with "pos+=searchFor.length" – hanshenrik这可能是这里最快的实现,但如果将“++pos”替换为“pos+=searchFor.length”,它会更快 – hanshenrik

function occurrences(str_, subStr) {
  let occurence_count = 0
  let pos = -subStr.length
  while ((pos = str_.indexOf(subStr, pos + subStr.length)) > -1) {
    occurence_count++
  }
  return occurence_count
}

How can I count the number of times a particular string occurs in another string.如何计算特定字符串在另一个字符串中出现的次数。 For example, this is what I am trying to do in Javascript:例如,这就是我要使用Javascript进行的操作:

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

Try this: 尝试这个:

function countString(str, search){
    var count=0;
    var index=str.indexOf(search);
    while(index!=-1){
        count++;
        index=str.indexOf(search,index+1);
    }
    return count;
}

 var s = "1";replaced word var a = "HRA"; //have to replace var str = document.getElementById("test").innerHTML; var count = str.split(a).length - 1; for (var i = 0; i < count; i++) { var s = "1"; var a = "HRA"; var str = document.getElementById("test").innerHTML; var res = str.replace(a, s); document.getElementById("test").innerHTML = res; } 

 <input " type="button" id="Btn_Validate" value="Validate" class="btn btn-info" /> <div class="textarea" id="test" contenteditable="true">HRABHRA</div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM