我该如何在一个字符串中统计另一个特定字符串出现的次数?例如,我想在Javascript中实现以下操作:
var temp = "This is a string.";
alert(temp.count("is")); //should output '2'
我该如何在一个字符串中统计另一个特定字符串出现的次数?例如,我想在Javascript中实现以下操作:
var temp = "This is a string.";
alert(temp.count("is")); //should output '2'
g
在正则表达式中代表全局匹配(即global),表示搜索整个字符串而不仅仅是找到第一个匹配项。这将匹配两次is
:
var temp = "This is a string.";
var count = (temp.match(/is/g) || []).length;
console.log(count);
如果没有匹配项,则返回0
:
var temp = "Hello World!";
var count = (temp.match(/is/g) || []).length;
console.log(count);
count = (str.match(/is/g) || []).length
来处理如果没有匹配的情况。 - Matt/** 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 https://dev59.com/eW865IYBdhLWcg3wEKOZ#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 `----´
我做了一个基准测试,我的函数比gumbo发布的正则表达式匹配函数快10倍以上。在我的测试字符串中,长度为25个字符,包含2个字符“o”。我在Safari浏览器上执行1,000,000次。
Safari 5.1
Benchmark> 总执行时间:5617毫秒(正则表达式)
Benchmark> 总执行时间:881毫秒(我的函数6.4倍快)
Firefox 4
Benchmark> 总执行时间:8547毫秒(正则表达式)
Benchmark> 总执行时间:634毫秒(我的函数13.5倍快)
编辑:我所做的更改
缓存子串长度
将类型转换为字符串
添加可选参数“allowOverlapping”
修复空子串的正确输出。
function countInstances(string, word) {
return string.split(word).length - 1;
}
console.log(countInstances("This is a string", "is"))
var theString = "This is a string.";
console.log(theString.split("is").length - 1);
我的解决方案:
var temp = "This is a string.";
function countOccurrences(str, value) {
var regExp = new RegExp(value, "gi");
return (str.match(regExp) || []).length;
}
console.log(countOccurrences(temp, 'is'));
countOcurrences('Hello...','.')==8
而不是3。 - Vitim.us您可以使用match
来定义这样的函数:
String.prototype.count = function(search) {
var m = this.match(new RegExp(search.toString().replace(/(?=[.\\+*?[^\]$(){}\|])/g, "\\"), "g"));
return m ? m.length:0;
}
return m ? m.length:-1;
。 - Conor O'Brien只是在进行代码高尔夫的Rebecca Chernoff的解决方案 :-)
alert(("This is a string.".match(/is/g) || []).length);
非正则表达式版本:
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
String.prototype.Count = function (find) {
return this.split(find).length - 1;
}
console.log("This is a string.".Count("is"));
这将返回2。
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};
这里是一种更慢、更易读的版本:
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;
};
'The char "a" only shows up twice'.timesCharExist('a');
编辑: (2013/12/16)
不要在Opera 12.16或更早版本中使用!它比正则表达式解决方案慢近2.5倍!
在Chrome上,这个解决方案将花费14毫秒至20毫秒处理100万个字符。
对于相同数量的字符,正则表达式解决方案需要11-14毫秒。
使用一个函数(在String.prototype
之外)大约需要10-13毫秒。
以下是所使用的代码:
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');
c=(c+'')[0]
改为 c=c+''
。