How to 카운트입니다 구체화하십시오 발생을 구체화하십시오?

어떻게 특정 문자열을 테스트타사의 횟수를 세는 다른 컨텍스트에서는 구체화하십시오. 예를 들어, 이것이 내가 해야 할 일이 사랑하려고 Javascript:

var temp = "This is a string.";
alert(temp.count("is")); //should output '2'
질문에 대한 의견 (2)
해결책

'G' 의 정규식이 (파선-짧은 에 대한 글로벌 ) 뿐 아니라 모든 문자열을 검색할 수 있는 첫 번째 에셋은 찾을 것이라고 말했습니다. 이 일치시킵니다 '는' 두 번:

<! - begin 스니핏: js 숨기십시오: 거짓값 콘솔: 진정한 바벨. &gt 거짓값 -; <! - 언어: &gt js 랭 -; var temp = 이는 string.&quot ";; var 카운트입니다 트렌크스 = (트럼퍼마치 (/ is / g) []). 콘솔드로그 (계산). 끝 - &lt 스니핏 >;!

이 경우, '0' 되돌려줍니다 일치시킵니다 없습니다.

<! - begin 스니핏: js 숨기십시오: 거짓값 콘솔: 진정한 바벨. &gt 거짓값 -; <! - 언어: &gt js 랭 -; var temp = &quot &quot Hello World!;;; var 카운트입니다 트렌크스 = (트럼퍼마치 (/ is / g) []). 콘솔드로그 (계산). 끝 - &lt 스니핏 >;!

해설 (17)
/** 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) {
            ++n;
            pos += step;
        } else break;
    }
    return n;
}

사용

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

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

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

알로보버라핑

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

일치시킵니다:

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

단위 테스트

  • https://jsfiddle.net/Victornpb/5axuh96u/

벤치마트

&gt. # 39, ve 브라운아저씨의 i& 벤치마크입니다 10 배 이상인 테스트 및 제 기능을 사용할 &gt. 빠른 일치시킵니다 올린 다음 정규 표현식 기능을 검보. 내 테스트 &gt. 문자열 (25) 은 자 이다. # 39, & # 39, 2 개 문자 실행 o&. 난 &gt. 수행되 1 000 000 000 회 사파리. &gt. &gt. 사파리 5.1 &gt. &gt. Benchmark&gt. 총 시간 실행: 5617 밀리초입니다 (정규 표현식) &gt. &gt. Benchmark&gt. 총 시간 실행: 881 밀리초입니다 (내 함수은 6.4x 빠름) &gt. &gt. Firefox 4 &gt. &gt. Benchmark&gt. 총 시간 실행: 8547 밀리초입니다 (렉스엑스프) &gt. &gt. Benchmark&gt. 총 시간 실행: 634 밀리초입니다 (내 함수은 13.5x 빠름) &gt. &gt. - &gt. &gt. 편집: # 39, ve 브라운아저씨의 I& 변경 &gt. &gt. - 문자열 길이를 캐싱된 &gt. &gt. - string 으로 타입 캐스팅 덧붙였다. &gt. &gt. - # 39, & # 39 allowOverlapping& 옵션임 덧붙였다. 매개변수입니다 &gt. &gt. - 고정식입니다 대한 올바른 출력입니다 &quot "; 빈 문자열 사례.

기스트

해설 (19)
function countInstances(string, word) {
   return string.split(word).length - 1;
}
해설 (10)

이 문제를 해결할 수 있습니다.

<! - begin 스니핏: js 숨기십시오: 거짓값 콘솔: 진정한 바벨. &gt 거짓값 -;

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

끝 - &lt 스니핏 >;!

해설 (5)

내 해결책:

<! - begin 스니핏: js 숨기십시오: 거짓값 콘솔: 진정한 바벨. &gt 거짓값 -;

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'));

끝 - &lt 스니핏 >;!

해설 (2)

'정의' 를 일치시킵니다 같은 기능을 사용할 수 있습니다.

String.prototype.count = function(search) {
    var m = this.match(new RegExp(search.toString().replace(/(?=[.\\+*?[^\]$(){}\|])/g, "\\"), "g"));
    return m ? m.length:0;
}
해설 (2)
  • 이 regex 비사양 version:*

<! - begin 스니핏: js 숨기십시오: 거짓값 콘솔: 진정한 바벨. &gt 거짓값 -;

 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

끝 - &lt 스니핏 >;!

해설 (2)

그냥 골프 코드 [레베카 허노프] (/users/181481/rebecca-chernoff) & # 39 의 [솔루션] (/a/4009768) :-)

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

<! - begin 스니핏: js 숨기십시오: 거짓값 콘솔: 진정한 바벨. &gt 거짓값 -;

String.prototype.Count = function (find) {
    return this.split(find).length - 1;
}

console.log("This is a string.".Count("is"));

끝 - &lt 스니핏 >;!

이 반환되므로 2.

해설 (1)

다음은 가장 빠른 함수은!

왜 그렇게 빠른?

39, t - Doesn& 확인란 챨 의해 챨 (1 개의 예외)

  • /Dev/raw/raw1 귈이예요 및 증분을 1 var (이 챨 카운트입니다 var) 은 증가 및 검사 vs. for 루프는 길이를 2 (일반적으로 var (i) · var 를 챨 카운트입니다)
  • 덜 var 방식을 사용합니다.
  • T # 39 Doesn& 사용하여, regex!
  • 사용하는 최적화된 함수 (기대해 본다)
  • 모든 작업이 될 수 있으므로 피하는 등 여러 작업을 인해 결합됨 속도 저하,

스트린고드프로토티페스타임샤렉리스트 함수 (c) = {var t = 0, 0, c = (c+& # 39, & # 39;) l = [0], 동시에 (l = 티스트린드쇼프 (c, l) +1) ++t 복귀하십시오 t};;

이것은 느려지고 더욱 판독값 버전:

    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;
    };

이건 느린 슬픔으로창백해지고 엇회전식, 긴 var 이름과 남용을 1 var.

바로 사용할 수 있어 이렇게 됩니다.

    'The char "a" only shows up twice'.timesCharExist('a');
  • 편집: (16/12/2013) *

39, don& 오페라 12.16 이상 사용할 수 없다! 이상 걸리기 때문에 거의 2.5x regex 솔루션이므로!

이 솔루션은 시행하십시오 14ms 및 20ms 사이에 있는 크롬 대한 1,000,000 자입니다.

Regex 는 동일한 11 14ms 이 솔루션을 적용했다.

함수를 사용하여 (바깥쪽인지가 '스트린고드프로토티페') 가 앨리어스보다 약 10 13ms.

다음은 사용되는 코드:

    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');

그 결과 모든 솔루션을 100,000 합니다!

참고: 이 기능을 스케쳐내 카운트입니다 1 개 이상의 챨 변경하십시오 (c+& # 39, & # 39;) 어디 'c = c = # 39, & # 39 c+& [0]' 에 ','

해설 (1)

<! - begin 스니핏: js 숨기십시오: 거짓값 콘솔: 진정한 바벨. &gt 거짓값 -;

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

끝 - &lt 스니핏 >;!

해설 (0)

Regex 는 '내 생각에는 목표를 크게 다르지 indexOf'. 반면 옥커런스 단순히 특정 문자열을 찾습니다 'indexOf' like ' [A-Z]' 즉 발견하리니 regex 와일드카드를 사용할 수 있습니다 모든 케이털 문자를 말을해야합니다 밝히지 않은 채 실제 문자.

예:

<! - begin 스니핏: js 숨기십시오: 거짓값 콘솔: 진정한 바벨. &gt 거짓값 -;

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

끝 - &lt 스니핏 >;!

해설 (0)

미래에 대해 이 점에 유념하십시오 수락됨 오토메이티드 스레드할 aspt 않은 사람은 항상 일반화할 경우 it, 정확한 값을 반품하십시오 않을 것이므로 이를 '$' 와 '.' 에서 경계감소 regex 사업자들은. # 39 의 버전을 더 잘 처리할 수 있는 모든 , here& 바늘:

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

기존 슈퍼 괜찮아요 하지만 난 오늘 필요가 있으며, 오직 돌아보 확인할 수 있어 이 같은 일이 된다. 상당히 빠른 작동됨 가져다줄래요.

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;
};
해설 (0)
       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");

) 은 다음과 같은 뜻이 있다. - [카운트입니다 substring) 가 있는 문자열의] (http://bit.ly/1yT1nAf) 를 단계적으로 설명.

해설 (0)

@Vittim.us 오토메이티드 바탕으로 한다. 같은 날, 나는 그의 방식은 제어입니다 보기입니다 쉽게 확장할 수 있지만, 내가 추가하는 데 필요한 경우 불감 및 제한값 단어 일치 지원할 수 있는 문장 부호. (예를 들면 &quot bath"; take a 가 &quot bath."; bathing&quot 아닌 ";)

Regex 는 문장 출신이다. https://stackoverflow.com/a/25575009/497745 (https://stackoverflow.com/questions/4328500/how-can-i-strip-all-punctuation-from-a-string-in-javascript-using-regex)

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

    string += "";
    subString += "";
    if (subString.length = 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;
}

이 경우 또는 향상을 별색 버그 수정 및 리팩터링 답을 주시면.

해설 (0)

<! - begin 스니핏: js 숨기십시오: 거짓값 콘솔: 진정한 바벨. &gt 거짓값 -;

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));

끝 - &lt 스니핏 >;!

자, 모두 사용하여 get_occurrence (var, 문자열) com/go/downloads_kr 에셋은 문자열에서 구체화하십시오.

해설 (0)

해봐.

<?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>
해설 (0)

아무도 없을 수 있지만, 이 슬라이드에서는 판매업체에서 it& # 39 의 优秀 뒤로를 재연됩니다 받을시간은 낼수있지않나 한 번 반복 및 화살표 기능 (펀 영광스럽게 고안되었습니다)

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

Regex 없이 간단한 버전:

<! - begin 스니핏: js 숨기십시오: 거짓값 콘솔: 참 - &gt.

var temp = "This is a string.";

var count = (temp.split('is').length - 1);

alert(count);

끝 - &lt 스니핏 >;!

해설 (1)