简体   繁体   English

Javascript 统计字符串中某个字符出现的次数

[英]Count the number of occurrences of a character in a string in Javascript

I need to count the number of occurrences of a character in a string.我需要计算字符串中某个字符出现的次数。

For example, suppose my string contains:例如,假设我的字符串包含:

var mainStr = "str1,str2,str3,str4";

I want to find the count of comma , character, which is 3. And the count of individual strings after the split along comma, which is 4.我想找到逗号,字符的计数,即 3。以及沿逗号拆分后的单个字符串的计数,即 4。

I also need to validate that each of the strings ie str1 or str2 or str3 or str4 should not exceed, say, 15 characters.我还需要验证每个字符串(即 str1 或 str2 或 str3 或 str4)不应超过 15 个字符。

I have updated this answer.我已经更新了这个答案。 I like the idea of using a match better, but it is slower:我更喜欢使用匹配的想法,但它更慢:

 console.log(("str1,str2,str3,str4".match(/,/g) || []).length); //logs 3 console.log(("str1,str2,str3,str4".match(new RegExp("str", "g")) || []).length); //logs 4

Use a regular expression literal if you know what you are searching for beforehand, if not you can use the RegExp constructor, and pass in the g flag as an argument.如果您事先知道要搜索的内容,请使用正则表达式文字,否则您可以使用RegExp构造函数,并将g标志作为参数传入。

match returns null with no results thus the || [] match返回null而没有结果,因此|| [] || []

The original answer I made in 2009 is below.我在 2009 年做出的原始答案如下。 It creates an array unnecessarily, but using a split is faster (as of September 2014).它不必要地创建了一个数组,但使用拆分更快(截至 2014 年 9 月)。 I'm ambivalent, if I really needed the speed there would be no question that I would use a split, but I would prefer to use match.我很矛盾,如果我真的需要速度,毫无疑问我会使用拆分,但我更喜欢使用匹配。

Old answer (from 2009):旧答案(从 2009 年开始):

If you're looking for the commas:如果您正在寻找逗号:

(mainStr.split(",").length - 1) //3

If you're looking for the str如果您正在寻找 str

(mainStr.split("str").length - 1) //4

Both in @Lo's answer and in my own silly performance test split comes ahead in speed, at least in Chrome, but again creating the extra array just doesn't seem sane.在@Lo 的回答和我自己的愚蠢性能测试中,速度都领先,至少在 Chrome 中是这样,但再次创建额外的数组似乎并不明智。

There are at least five ways.至少有五种方法。 The best option, which should also be the fastest (owing to the native RegEx engine) is placed at the top.最好的选项,也应该是最快的(由于本机 RegEx 引擎)放在顶部。

Method 1方法一

("this is foo bar".match(/o/g)||[]).length;
// returns 2

Method 2方法二

"this is foo bar".split("o").length - 1;
// returns 2

Split not recommended as it is resource hungry.不推荐拆分,因为它很耗资源。 It allocates new instances of 'Array' for each match.它为每个匹配分配新的 'Array' 实例。 Don't try it for a >100MB file via FileReader.不要尝试通过 FileReader 获取 >100MB 的文件。 You can observe the exact resource usage using Chrome's profiler option.您可以使用Chrome 的分析器选项观察确切的资源使用情况。

Method 3方法三

    var stringsearch = "o"
       ,str = "this is foo bar";
    for(var count=-1,index=-2; index != -1; count++,index=str.indexOf(stringsearch,index+1) );
// returns 2

Method 4方法四

Searching for a single character搜索单个字符

    var stringsearch = "o"
       ,str = "this is foo bar";
    for(var i=count=0; i<str.length; count+=+(stringsearch===str[i++]));
     // returns 2

Method 5方法五

Element mapping and filtering.元素映射和过滤。 This is not recommended due to its overall resource preallocation rather than using Pythonian 'generators':不建议这样做,因为它的整体资源预分配而不是使用 Pythonian 'generators':

    var str = "this is foo bar"
    str.split('').map( function(e,i){ if(e === 'o') return i;} )
                 .filter(Boolean)
    //>[9, 10]
    [9, 10].length
    // returns 2

Share: I made this gist , with currently 8 methods of character-counting, so we can directly pool and share our ideas - just for fun, and perhaps some interesting benchmarks :)分享:我提出了这个要点,目前有 8 种字符计数方法,所以我们可以直接汇集和分享我们的想法 - 只是为了好玩,也许还有一些有趣的基准:)

Add this function to sting prototype :将此函数添加到 sting 原型:

String.prototype.count=function(c) { 
  var result = 0, i = 0;
  for(i;i<this.length;i++)if(this[i]==c)result++;
  return result;
};

usage:用法:

console.log("strings".count("s")); //2

Simply, use the split to find out the number of occurrences of a character in a string.简单地说,使用拆分来找出字符串中某个字符的出现次数。

mainStr.split(',').length // gives 4 which is the number of strings after splitting using delimiter comma mainStr.split(',').length // 给出 4,即使用分隔符逗号分割后的字符串数

mainStr.split(',').length - 1 // gives 3 which is the count of comma mainStr.split(',').length - 1 // 给出 3,这是逗号的计数

A quick Google search got this (from http://www.codecodex.com/wiki/index.php?title=Count_the_number_of_occurrences_of_a_specific_character_in_a_string#JavaScript )一个快速的谷歌搜索得到了这个(来自http://www.codecodex.com/wiki/index.php?title=Count_the_number_of_occurrences_of_a_specific_character_in_a_string#JavaScript

String.prototype.count=function(s1) { 
    return (this.length - this.replace(new RegExp(s1,"g"), '').length) / s1.length;
}

Use it like this:像这样使用它:

test = 'one,two,three,four'
commas = test.count(',') // returns 3

You can also rest your string and work with it like an array of elements using您还可以休息您的字符串并像使用元素数组一样使用它

 const mainStr = 'str1,str2,str3,str4'; const commas = [...mainStr].filter(l => l === ',').length; console.log(commas);

Or或者

 const mainStr = 'str1,str2,str3,str4'; const commas = [...mainStr].reduce((a, c) => c === ',' ? ++a : a, 0); console.log(commas);

Here is a similar solution, but it uses Array.prototype.reduce这是一个类似的解决方案,但它使用Array.prototype.reduce

function countCharacters(char, string) {
  return string.split('').reduce((acc, ch) => ch === char ? acc + 1: acc, 0)
}

As was mentioned, String.prototype.split works much faster than String.prototype.replace .如前所述, String.prototype.splitString.prototype.replace工作得快得多。

ok, an other one with regexp - probably not fast, but short and better readable then others, in my case just '_' to count好的,另一个带有正则表达式的 - 可能不快,但比其他的短且可读性更好,在我的情况下只是'_'

key.replace(/[^_]/g,'').length

just remove everything that does not look like your char but it does not look nice with a string as input只需删除所有看起来不像您的字符但使用字符串作为输入看起来不好看的所有内容

If you are using lodash, the _.countBy method will do this:如果你使用 lodash,_. countBy方法会这样做:

_.countBy("abcda")['a'] //2

This method also work with array:此方法也适用于数组:

_.countBy(['ab', 'cd', 'ab'])['ab'] //2

I have found that the best approach to search for a character in a very large string (that is 1 000 000 characters long, for example) is to use the replace() method.我发现在非常大的字符串(例如 1 000 000 个字符长)中搜索字符的最佳方法是使用replace()方法。

window.count_replace = function (str, schar) {
    return str.length - str.replace(RegExp(schar), '').length;
};

You can see yet another JSPerf suite to test this method along with other methods of finding a character in a string.您可以看到另一个 JSPerf套件来测试此方法以及在字符串中查找字符的其他方法。

Performance of Split vs RegExp拆分与正则表达式的性能

 var i = 0; var split_start = new Date().getTime(); while (i < 30000) { "1234,453,123,324".split(",").length -1; i++; } var split_end = new Date().getTime(); var split_time = split_end - split_start; i= 0; var reg_start = new Date().getTime(); while (i < 30000) { ("1234,453,123,324".match(/,/g) || []).length; i++; } var reg_end = new Date().getTime(); var reg_time = reg_end - reg_start; alert ('Split Execution time: ' + split_time + "\n" + 'RegExp Execution time: ' + reg_time + "\n");

I made a slight improvement on the accepted answer, it allows to check with case-sensitive/case-insensitive matching, and is a method attached to the string object:我对接受的答案做了一点改进,它允许检查区分大小写/不区分大小写的匹配,并且是附加到字符串对象的方法:

String.prototype.count = function(lit, cis) {
    var m = this.toString().match(new RegExp(lit, ((cis) ? "gi" : "g")));
    return (m != null) ? m.length : 0;
}

lit is the string to search for ( such as 'ex' ), and cis is case-insensitivity, defaulted to false, it will allow for choice of case insensitive matches. lit是要搜索的字符串(例如 'ex' ),而 cis 是不区分大小写的,默认为 false,它将允许选择不区分大小写的匹配项。


To search the string 'I love StackOverflow.com' for the lower-case letter 'o' , you would use: 要在字符串'I love StackOverflow.com'中搜索小写字母'o' ,您可以使用:

var amount_of_os = 'I love StackOverflow.com'.count('o');

amount_of_os would be equal to 2 . amount_of_os将等于2


If we were to search the same string again using case-insensitive matching, you would use: 如果我们要使用不区分大小写的匹配再次搜索相同的字符串,您将使用:

 var amount_of_os = 'I love StackOverflow.com'.count('o', true);

This time, amount_of_os would be equal to 3 , since the capital O from the string gets included in the search.这一次, amount_of_os将等于3 ,因为字符串中的大写O被包含在搜索中。

Easiest way i found out...我发现的最简单的方法...

Example-例子-

str = 'mississippi';

function find_occurences(str, char_to_count){
    return str.split(char_to_count).length - 1;
}

find_occurences(str, 'i') //outputs 4

Here is my solution.这是我的解决方案。 Lots of solution already posted before me.很多解决方案已经在我面前发布。 But I love to share my view here.但我喜欢在这里分享我的观点。

const mainStr = 'str1,str2,str3,str4';

const commaAndStringCounter = (str) => {
  const commas = [...str].filter(letter => letter === ',').length;
  const numOfStr = str.split(',').length;

  return `Commas: ${commas}, String: ${numOfStr}`;
}

// Run the code
console.log(commaAndStringCounter(mainStr)); // Output: Commas: 3, String: 4

Here you find my REPL在这里你可以找到我的 REPL

s = 'dir/dir/dir/dir/'
for(i=l=0;i<s.length;i++)
if(s[i] == '/')
l++

I was working on a small project that required a sub-string counter.我正在做一个需要子字符串计数器的小项目。 Searching for the wrong phrases provided me with no results, however after writing my own implementation I have stumbled upon this question.搜索错误的短语没有给我任何结果,但是在编写了自己的实现之后,我偶然发现了这个问题。 Anyway, here is my way, it is probably slower than most here but might be helpful to someone:无论如何,这是我的方式,它可能比这里的大多数都慢,但可能对某人有帮助:

function count_letters() {
var counter = 0;

for (var i = 0; i < input.length; i++) {
    var index_of_sub = input.indexOf(input_letter, i);

    if (index_of_sub > -1) {
        counter++;
        i = index_of_sub;
    }
}

http://jsfiddle.net/5ZzHt/1/ http://jsfiddle.net/5ZzHt/1/

Please let me know if you find this implementation to fail or do not follow some standards!如果您发现此实施失败或不遵循某些标准,请告诉我! :) :)

UPDATE You may want to substitute:更新您可能想要替换:

    for (var i = 0; i < input.length; i++) {

With:和:

for (var i = 0, input_length = input.length; i < input_length; i++) {

Interesting read discussing the above: http://www.erichynds.com/blog/javascript-length-property-is-a-stored-value有趣的阅​​读讨论上述内容: http ://www.erichynds.com/blog/javascript-length-property-is-a-stored-value

I just did a very quick and dirty test on repl.it using Node v7.4.我刚刚使用 Node v7.4 对repl.it做了一个非常快速和肮脏的测试。 For a single character, the standard for loop is quickest:对于单个字符,标准 for 循环是最快的:

Some code :一些代码

// winner!
function charCount1(s, c) {
    let count = 0;
    c = c.charAt(0); // we save some time here
    for(let i = 0; i < s.length; ++i) {
        if(c === s.charAt(i)) {
            ++count;
        }
    }
    return count;
}

function charCount2(s, c) {
    return (s.match(new RegExp(c[0], 'g')) || []).length;
}

function charCount3(s, c) {
    let count = 0;
    for(ch of s) {
        if(c === ch) {
            ++count;
        }
    }
    return count;
}

function perfIt() {
    const s = 'Hello, World!';
    const c = 'o';

    console.time('charCount1');
    for(let i = 0; i < 10000; i++) {
        charCount1(s, c);
    }
    console.timeEnd('charCount1');
    
    console.time('charCount2');
    for(let i = 0; i < 10000; i++) {
        charCount2(s, c);
    }
    console.timeEnd('charCount2');
    
    console.time('charCount3');
    for(let i = 0; i < 10000; i++) {
        charCount2(s, c);
    }
    console.timeEnd('charCount3');
}

Results from a few runs :几次运行的结果

perfIt()
charCount1: 3.301ms
charCount2: 11.652ms
charCount3: 174.043ms
undefined

perfIt()
charCount1: 2.110ms
charCount2: 11.931ms
charCount3: 177.743ms
undefined

perfIt()
charCount1: 2.074ms
charCount2: 11.738ms
charCount3: 152.611ms
undefined

perfIt()
charCount1: 2.076ms
charCount2: 11.685ms
charCount3: 154.757ms
undefined

Update 2021-Feb-10 : Fixed typo in repl.it demo 2021 年 2 月 10 日更新:修复了 repl.it 演示中的错字

Update 2020-Oct-24 : Still the case with Node.js 12 (play with it yourself here) 2020 年 10 月 24 日更新Node.js 12 仍然如此(在这里自己玩)

What about string.split(desiredCharecter).length-1 string.split(desiredCharecter).length-1 怎么样

Example:例子:

var str = "hellow how is life"; var str = "你好,生活怎么样"; var len = str.split("h").length-1; var len = str.split("h").length-1; will give count 2 for character "h" in the above string;将为上述字符串中的字符“h”提供计数 2;

The fastest method seems to be via the index operator:最快的方法似乎是通过索引运算符:

 function charOccurances (str, char) { for (var c = 0, i = 0, len = str.length; i < len; ++i) { if (str[i] == char) { ++c; } } return c; } console.log( charOccurances('example/path/script.js', '/') ); // 2

Or as a prototype function:或者作为原型函数:

 String.prototype.charOccurances = function (char) { for (var c = 0, i = 0, len = this.length; i < len; ++i) { if (this[i] == char) { ++c; } } return c; } console.log( 'example/path/script.js'.charOccurances('/') ); // 2

function len(text,char){

return text.innerText.split(string).length
}

console.log(len("str1,str2,str3,str4",","))

This is a very short function.这是一个非常简短的函数。

I know I am late to the party here but I was rather baffled no one answered this with the most basic of approaches.我知道我在这里聚会迟到了,但我很困惑没有人用最基本的方法回答这个问题。 A large portion of the answers provided by the community for this question are iteration based but all are moving over strings on a per-character basis which is not really efficient.社区为这个问题提供的大部分答案都是基于迭代的,但所有答案都是基于每个字符移动字符串,这并不是很有效。

When dealing with a large string that contains thousands of characters walking over each character to get the occurance count can become rather extraneous not to mention a code-smell.在处理包含数千个字符的大字符串时,遍历每个字符以获取出现次数可能变得相当无关紧要,更不用说代码气味了。 The below solutions take advantage of slice , indexOf and the trusted traditional while loop.以下解决方案利用sliceindexOf和受信任的传统while循环。 These approaches prevent us having to walk over each character and will greatly speed up the time it takes to count occurances.这些方法使我们不必遍历每个字符,并将大大加快计算出现次数的时间。 These follow similar logic to that you'd find in parsers and lexical analyzers that require string walks.这些遵循与您在需要字符串遍历的解析器和词法分析器中发现的类似逻辑。

Using with Slice与切片一起使用

In this approach we are leveraging slice and with every indexOf match we will move our way through the string and eliminate the previous searched potions.在这种方法中,我们利用了slice并且对于每个indexOf匹配,我们将在字符串中移动并消除先前搜索的药水。 Each time we call indexOf the size of the string it searches will be smaller.每次我们调用indexOf时,它搜索的字符串的大小都会变小。

function countChar (char: string, search: string): number {
  
  let num: number = 0;
  let str: string = search;
  let pos: number = str.indexOf(char);
  
  while(pos > -1) {
    str = str.slice(pos + 1);
    pos = str.indexOf(char);
    num++;
  }

  return num;

}

// Call the function
countChar('x', 'foo x bar x baz x') // 3

Using with IndexOf from position从位置与 IndexOf 一起使用

Similar to the first approach using slice but instead of augmenting the string we are searching it will leverage the from parameter in indexOf method.类似于使用slice的第一种方法,但不是增加我们正在搜索的字符串,它将利用indexOf方法中的from参数。

function countChar (char: string, str: string): number {
  
  let num: number = 0;
  let pos: number = str.indexOf(char);
  
  while(pos > -1) {
    pos = str.indexOf(char, pos + 1);
    num++;
  }

  return num;

}

// Call the function
countChar('x', 'foo x bar x baz x') // 3

Personally, I go for the second approach over the first, but both are fine and performant when dealing with large strings but also smaller sized ones too.就我个人而言,我倾向于第二种方法而不是第一种方法,但是在处理大字符串时两者都很好并且性能更好,但也适用于较小的字符串。

It's amazing that in 13 years, this answer hasn't shown up.令人惊讶的是,13 年来,这个答案还没有出现。 Intuitively, it seems like it should be fastest:直觉上,它似乎应该是最快的:

const s = "The quick brown fox jumps over the lazy dog.";
const oCount = s.length - s.replaceAll('o', '').length;

If there are only two kinds of character in the string, then this is faster still:如果字符串中只有两种字符,那么这样更快:


const s = "001101001";
const oneCount = s.replaceAll('0', '').length;

I'm using Node.js v.6.0.0 and the fastest is the one with index (the 3rd method in Lo Sauer's answer).我正在使用 Node.js v.6.0.0,最快的是带索引的(Lo Sauer 回答中的第三种方法)。

The second is:第二个是:

 function count(s, c) { var n = 0; for (let x of s) { if (x == c) n++; } return n; }

Here's one just as fast as the split() and the replace methods, which are a tiny bit faster than the regex method (in Chrome and Firefox both).这是一个与split()和 replace 方法一样快的方法,它们比正则表达式方法(在 Chrome 和 Firefox 中)快一点。

let num = 0;
let str = "str1,str2,str3,str4";
//Note: Pre-calculating `.length` is an optimization;
//otherwise, it recalculates it every loop iteration.
let len = str.length;
//Note: Don't use a `for (... of ...)` loop, it's slow!
for (let charIndex = 0; charIndex < len; ++charIndex) {
  if (str[charIndex] === ',') {
    ++num;
  }
}

And there is:还有:

function character_count(string, char, ptr = 0, count = 0) {
    while (ptr = string.indexOf(char, ptr) + 1) {count ++}
    return count
}

Works with integers too!也适用于整数!

 var mainStr = "str1,str2,str3,str4"; var splitStr = mainStr.split(",").length - 1; // subtracting 1 is important! alert(splitStr);

Splitting into an array gives us a number of elements, which will always be 1 more than the number of instances of the character.拆分成一个数组给了我们一些元素,这些元素总是比字符实例的数量多 1。 This may not be the most memory efficient, but if your input is always going to be small, this is a straight-forward and easy to understand way to do it.这可能不是最节省内存的,但如果您的输入总是很小,这是一种直接且易于理解的方法。

If you need to parse very large strings (greater than a few hundred characters), or if this is in a core loop that processes large volumes of data, I would recommend a different strategy.如果您需要解析非常大的字符串(超过几百个字符),或者如果这是在处理大量数据的核心循环中,我会推荐一种不同的策略。

 String.prototype.reduce = Array.prototype.reduce; String.prototype.count = function(c) { return this.reduce(((n, x) => n + (x === c? 1: 0)), 0) }; const n = "bugs bunny was here".count("b") console.log(n)

Similar to the prototype based above, but does not allocate an array for the string.类似于上面的原型,但是没有为字符串分配数组。 Allocation is the problem of nearly every version above, except the loop variants.分配是上面几乎每个版本的问题,除了循环变体。 This avoids loop code, reusing the browser implemented Array.reduce function.这避免了循环代码,重用浏览器实现的 Array.reduce function。

The following uses a regular expression to test the length.下面使用正则表达式来测试长度。 testex ensures you don't have 16 or greater consecutive non-comma characters. testex 确保您没有 16 个或更多连续的非逗号字符。 If it passes the test, then it proceeds to split the string.如果它通过了测试,那么它将继续拆分字符串。 counting the commas is as simple as counting the tokens minus one.计算逗号就像计算标记减一一样简单。

var mainStr = "str1,str2,str3,str4";
var testregex = /([^,]{16,})/g;
if (testregex.test(mainStr)) {
  alert("values must be separated by commas and each may not exceed 15 characters");
} else {
  var strs = mainStr.split(',');
  alert("mainStr contains " + strs.length + " substrings separated by commas.");
  alert("mainStr contains " + (strs.length-1) + " commas.");
}

My solution:我的解决方案:

function countOcurrences(str, value){
   var regExp = new RegExp(value, "gi");
   return str.match(regExp) ? str.match(regExp).length : 0;  
}

The fifth method in Leo Sauers answer fails, if the character is on the beginning of the string.如果字符位于字符串的开头,则 Leo Sauers 答案中的第五种方法失败。 eg例如

var needle ='A',
  haystack = 'AbcAbcAbc';

haystack.split('').map( function(e,i){ if(e === needle) return i;} )
  .filter(Boolean).length;

will give 2 instead of 3, because the filter funtion Boolean gives false for 0.将给出 2 而不是 3,因为过滤器函数 Boolean 为 0 给出 false。

Other possible filter function:其他可能的过滤功能:

haystack.split('').map(function (e, i) {
  if (e === needle) return i;
}).filter(function (item) {
  return !isNaN(item);
}).length;

one more answer:还有一个答案:

function count(string){
  const count={}
  
  string.split('').forEach(char=>{
    count[char] = count[char] ? (count[char]+1) : 1;
  })
  
  return count
}

console.log(count("abfsdfsddsfdfdsfdsfdsfda"))

I know this might be an old question but I have a simple solution for low-level beginners in JavaScript.我知道这可能是一个老问题,但我为 JavaScript 的低级初学者提供了一个简单的解决方案。

As a beginner, I could only understand some of the solutions to this question so I used two nested FOR loops to check each character against every other character in the string, incrementing a count variable for each character found that equals that character.作为一个初学者,我只能理解这个问题的一些解决方案,所以我使用两个嵌套的FOR循环来检查每个字符与字符串中的每个其他字符,为找到的每个字符增加一个计数变量等于该字符。

I created a new blank object where each property key is a character and the value is how many times each character appeared in the string(count).我创建了一个新的空白对象,其中每个属性键都是一个字符,值是每个字符在字符串中出现的次数(计数)。

Example function:-示例功能:-

function countAllCharacters(str) {
  var obj = {};
  if(str.length!==0){
    for(i=0;i<str.length;i++){
      var count = 0;
      for(j=0;j<str.length;j++){
        if(str[i] === str[j]){
          count++;
        }
      }
      if(!obj.hasOwnProperty(str[i])){
        obj[str[i]] = count;
      }
    }
  }
  return obj;
}

I believe you will find the below solution to be very short, very fast, able to work with very long strings, able to support multiple character searches, error proof, and able to handle empty string searches.我相信您会发现以下解决方案非常短、非常快、能够处理非常长的字符串、能够支持多字符搜索、防错以及能够处理空字符串搜索。

function substring_count(source_str, search_str, index) {
    source_str += "", search_str += "";
    var count = -1, index_inc = Math.max(search_str.length, 1);
    index = (+index || 0) - index_inc;
    do {
        ++count;
        index = source_str.indexOf(search_str, index + index_inc);
    } while (~index);
    return count;
}

Example usage:示例用法:

 console.log(substring_count("Lorem ipsum dolar un sit amet.", "m ")) function substring_count(source_str, search_str, index) { source_str += "", search_str += ""; var count = -1, index_inc = Math.max(search_str.length, 1); index = (+index || 0) - index_inc; do { ++count; index = source_str.indexOf(search_str, index + index_inc); } while (~index); return count; }

The above code fixes the major performance bug in Jakub Wawszczyk's that the code keeps on looks for a match even after indexOf says there is none and his version itself is not working because he forgot to give the function input parameters.上面的代码修复了 Jakub Wawszczyk 中的主要性能错误,即即使在 indexOf 表示没有匹配项并且他的版本本身由于他忘记提供函数输入参数而无法正常工作之后,该代码仍会继续寻找匹配项。

var a = "acvbasbb";
var b= {};
for (let i=0;i<a.length;i++){
    if((a.match(new RegExp(a[i], "g"))).length > 1){
        b[a[i]]=(a.match(new RegExp(a[i], "g"))).length;
    }
}
console.log(b);

In javascript you can use above code to get occurrence of a character in a string.在 javascript 中,您可以使用上面的代码来获取字符串中某个字符的出现。

My solution with ramda js:我使用 ramda js 的解决方案:

const testString = 'somestringtotest'

const countLetters = R.compose(
  R.map(R.length),
  R.groupBy(R.identity),
  R.split('')
)

countLetters(testString)

Link to REPL. 链接到 REPL。

The function takes string str as parameter and counts occurrence of each unique characters in the string.该函数将字符串 str 作为参数,并计算字符串中每个唯一字符的出现次数。 The result comes in key - value pair for each character.结果出现在每个字符的键值对中。

var charFoundMap = {};//object defined
    for (var i = 0; i < str.length; i++) {

       if(!charFoundMap[ str[i] ])  {
        charFoundMap[ str[i] ]=1;
       } 
       else
       charFoundMap[ str[i] ] +=1;
       //if object does not contain this 
    }
    return charFoundMap;

} 
let str = "aabgrhaab"
let charMap = {}

for(let char of text) {
   if(charMap.hasOwnProperty(char)){
      charMap[char]++
   } else {
     charMap[char] = 1
   }
}

console.log(charMap);控制台.log(charMap); //{a: 4, b: 2, g: 1, r: 1, h: 1} //{a: 4, b: 2, g: 1, r: 1, h: 1}

There is a very tricky way, but it is in reverse:有一个非常棘手的方法,但它是相反的:

const sampleStringText = "/john/dashboard/language";

Assume the above sample, for counting the number of forward-slashs you can do like this:假设上面的示例,要计算正斜杠的数量,您可以这样做:

console.log( sampleStringText.split('/') - 1 );

So I recommended to use a function for it (TypeScript):所以我建议为它使用一个函数(TypeScript):

const counter = (sentence: string, char: string): number => sentence.split(char) - 1;

I just did it using reduce function on a generated array.我只是在生成的数组上使用 reduce 函数做到了。 May not be perfeft, but I like this one.可能不完美,但我喜欢这个。

Cons: counts only single character, not word occurences.缺点:只计算单个字符,不计算单词出现次数。

    let str = "this is a test string";
    let count = [0, ...str].reduce(a, b => a + (b == "s"));
    // returns 4

 var i = 0; var split_start = new Date().getTime(); while (i < 30000) { "1234,453,123,324".split(",").length -1; i++; } var split_end = new Date().getTime(); var split_time = split_end - split_start; i= 0; var reg_start = new Date().getTime(); while (i < 30000) { ("1234,453,123,324".match(/,/g) || []).length; i++; } var reg_end = new Date().getTime(); var reg_time = reg_end - reg_start; alert ('Split Execution time: ' + split_time + "\n" + 'RegExp Execution time: ' + reg_time + "\n");

This below is the simplest logic, which is very easy to understand下面这个是最简单的逻辑,很容易理解

  //Demo string with repeat char 
  let str = "Coffee"
  //Splitted the str into an char array for looping
  let strArr = str.split("")
  //This below is the final object which holds the result
  let obj = {};
  //This loop will count char (You can also use traditional one for loop)
  strArr.forEach((value,index)=>{
      //If the char exists in the object it will simple increase its value
      if(obj[value] != undefined)
      {
          obj[value] = parseInt(obj[value]) + 1;
      }//else it will add the new one with initializing 1
      else{
          obj[value] =1;
      }      
  });

  console.log("Char with Count:",JSON.stringify(obj)); //Char with Count:{"C":1,"o":1,"f":2,"e":2}

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

相关问题 计算句子中出现的字符数 - count number of character occurrences in a sentence 如何使用文本框计算字符串中字符出现的次数? - How do I count the number of occurrences of a character in a string using textboxes? ES6 / lodash计算字符串中字符的出现次数 - ES6 / lodash count the number of occurrences of a character in a string 如何计算字符串中字符的出现次数而不是其中之一? - how to Count the number of occurrences of a character in a string but not one of them? 关于 Javascript 表达式的任何建议,以计算 Javascript 中特定字符串的出现次数 - Any suggestion on Javascript expression to count the number of occurrences of a particular string in Javascript 查找字符串中出现的许多字符 - Find a number of occurrences of character in string 计算列表中出现在javascript字符串中的项目的出现次数 - count the number of occurrences of items in a list that appear in a string in javascript 使用Javascript计算包含特定字符串的数组中唯一出现次数 - Count the number of unique occurrences in an array that contain a specific string with Javascript 有没有办法计算 DOM 中字符串的出现次数? (javascript/jQuery) - Is there a way to count number of occurrences of a string in the DOM? (javascript/jQuery) 字符串中的数组出现Javascript计数 - Javascript count occurrences of Array in String
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM