Count the number of occurrences of a character in a string in Javascript

后端 未结 30 2496
礼貌的吻别
礼貌的吻别 2020-11-22 02:33

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\";         


        
30条回答
  •  借酒劲吻你
    2020-11-22 03:22

    The following uses a regular expression to test the length. testex ensures you don't have 16 or greater consecutive non-comma characters. 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.");
    }
    

提交回复
热议问题