[removed] How many times a character occurs in a string?

前端 未结 6 2102
傲寒
傲寒 2020-12-13 03:15

Is there a simple way to check how many times a character appears in a String?

6条回答
  •  我在风中等你
    2020-12-13 03:56

    This counts a in below example:

    str = "A man is as good as his word";
    alert(str.split('a').length-1);
    

    If you want case insensitive you'd want something like

    alert(str.split( new RegExp( "a", "gi" ) ).length-1);
    

    So that it grabs "A" and "a" ... "g" flag isn't really needed, but you do need the "i" flag

提交回复
热议问题