어떻게 특정 문자열을 테스트타사의 횟수를 세는 다른 컨텍스트에서는 구체화하십시오. 예를 들어, 이것이 내가 해야 할 일이 사랑하려고 Javascript:
var temp = "This is a string.";
alert(temp.count("is")); //should output '2'
'G' 의 정규식이 (파선-짧은 에 대한 글로벌 ) 뿐 아니라 모든 문자열을 검색할 수 있는 첫 번째 에셋은 찾을 것이라고 말했습니다. 이 일치시킵니다 '는' 두 번:
<! - begin 스니핏: js 숨기십시오: 거짓값 콘솔: 진정한 바벨. > 거짓값 -; <! - 언어: > js 랭 -; var temp = 이는 string." ";; var 카운트입니다 트렌크스 = (트럼퍼마치 (/ is / g) []). 콘솔드로그 (계산). 끝 - < 스니핏 >;!
이 경우, '0' 되돌려줍니다 일치시킵니다 없습니다.
<! - begin 스니핏: js 숨기십시오: 거짓값 콘솔: 진정한 바벨. > 거짓값 -; <! - 언어: > js 랭 -; var temp = " " Hello World!;;; var 카운트입니다 트렌크스 = (트럼퍼마치 (/ is / g) []). 콘솔드로그 (계산). 끝 - < 스니핏 >;!
/** 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
* @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;
}
occurrences("foofoofoo", "bar"); //0
occurrences("foofoofoo", "foo"); //3
occurrences("foofoofoo", "foofoo"); //1
occurrences("foofoofoo", "foofoo", true); //2
일치시킵니다:
foofoofoo
1 `----´
2 `----´
>. # 39, ve 브라운아저씨의 i& 벤치마크입니다 10 배 이상인 테스트 및 제 기능을 사용할 >. 빠른 일치시킵니다 올린 다음 정규 표현식 기능을 검보. 내 테스트 >. 문자열 (25) 은 자 이다. # 39, & # 39, 2 개 문자 실행 o&. 난 >. 수행되 1 000 000 000 회 사파리. >. >. 사파리 5.1 >. >. Benchmark>. 총 시간 실행: 5617 밀리초입니다 (정규 표현식) >. >. Benchmark>. 총 시간 실행: 881 밀리초입니다 (내 함수은 6.4x 빠름) >. >. Firefox 4 >. >. Benchmark>. 총 시간 실행: 8547 밀리초입니다 (렉스엑스프) >. >. Benchmark>. 총 시간 실행: 634 밀리초입니다 (내 함수은 13.5x 빠름) >. >. - >. >. 편집: # 39, ve 브라운아저씨의 I& 변경 >. >. - 문자열 길이를 캐싱된 >. >. - string 으로 타입 캐스팅 덧붙였다. >. >. - # 39, & # 39 allowOverlapping& 옵션임 덧붙였다. 매개변수입니다 >. >. - 고정식입니다 대한 올바른 출력입니다 " "; 빈 문자열 사례.
내 해결책:
<! - begin 스니핏: js 숨기십시오: 거짓값 콘솔: 진정한 바벨. > 거짓값 -;
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'));
끝 - < 스니핏 >;!
<! - begin 스니핏: js 숨기십시오: 거짓값 콘솔: 진정한 바벨. > 거짓값 -;
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
끝 - < 스니핏 >;!
다음은 가장 빠른 함수은!
왜 그렇게 빠른?
스트린고드프로토티페스타임샤렉리스트 함수 (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');
이 솔루션은 시행하십시오 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]' 에 ','
Regex 는 '내 생각에는 목표를 크게 다르지 indexOf'. 반면 옥커런스 단순히 특정 문자열을 찾습니다 'indexOf' like ' [A-Z]' 즉 발견하리니 regex 와일드카드를 사용할 수 있습니다 모든 케이털 문자를 말을해야합니다 밝히지 않은 채 실제 문자.
예:
<! - begin 스니핏: js 숨기십시오: 거짓값 콘솔: 진정한 바벨. > 거짓값 -;
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);
끝 - < 스니핏 >;!
미래에 대해 이 점에 유념하십시오 수락됨 오토메이티드 스레드할 aspt 않은 사람은 항상 일반화할 경우 it, 정확한 값을 반품하십시오 않을 것이므로 이를 '$' 와 '.' 에서 경계감소 regex 사업자들은. # 39 의 버전을 더 잘 처리할 수 있는 모든 , here& 바늘:
function occurrences (haystack, needle) {
var _needle = needle
.replace(/\[/g, '\\[')
.replace(/\]/g, '\\]')
return (
haystack.match(new RegExp('[' + _needle + ']', 'g')) || []
).length
}
기존 슈퍼 괜찮아요 하지만 난 오늘 필요가 있으며, 오직 돌아보 확인할 수 있어 이 같은 일이 된다. 상당히 빠른 작동됨 가져다줄래요.
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");
) 은 다음과 같은 뜻이 있다. - [카운트입니다 substring) 가 있는 문자열의] (http://bit.ly/1yT1nAf) 를 단계적으로 설명.
@Vittim.us 오토메이티드 바탕으로 한다. 같은 날, 나는 그의 방식은 제어입니다 보기입니다 쉽게 확장할 수 있지만, 내가 추가하는 데 필요한 경우 불감 및 제한값 단어 일치 지원할 수 있는 문장 부호. (예를 들면 " bath"; take a 가 " bath."; bathing" 아닌 ";)
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) 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;
}
이 경우 또는 향상을 별색 버그 수정 및 리팩터링 답을 주시면.
<! - begin 스니핏: js 숨기십시오: 거짓값 콘솔: 진정한 바벨. > 거짓값 -;
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));
끝 - < 스니핏 >;!
자, 모두 사용하여 get_occurrence (var, 문자열) com/go/downloads_kr 에셋은 문자열에서 구체화하십시오.