Count of specific character (e.g. # of commas) in a Variable's content?

@cvc8445, I think we've shown you several easy ways to accomplish your task, and perhaps a few complicated ways. :smile:

In the interest of providing a more general solution that also handles any length of an arbitrary string, I submit the following Macro with JXA script. The core of the script is still quite simple and readable:

var sourceStr  = kmeApp.getvariable("Local__SourceStr",  {instance: kmInst}) || "aaa XYZ bbb XYZ ccc XYZ ddd";
var strToCount = kmeApp.getvariable("Local__StringToCount",  {instance: kmInst}) || "XYZ";
  
  //--- COUNT THE NUMBER OF OCCURRENCES ---
  var numOccur = sourceStr.split(strToCount).length - 1

I prefer a more focused script that, while working in the general case, still returns directly the answer we are looking for, without having to do further parsing to get it. The script simply returns the integer number of occurrences to a KM Variable.

This macro and script are provided as a learning tool, and example, to show you how to use certain features of KM. You will need to adapt it, or use parts of it, to your own macro/script.

To that end, if you have any questions, comments, issues, or suggestions about this, please feel free to post.


Example Output

Base Case: Simple, 1-character String
image

Expanded Case: Multi-character String
image


MACRO:   Count Number of Occurrences of String [Example]


#### DOWNLOAD:
<a class="attachment" href="/uploads/default/original/3X/9/5/9567e13e55cdb626cada747065c8d4f743574bcf.kmmacros">Count Number of Occurrences of String [Example].kmmacros</a> (12 KB)
**Note: This Macro was uploaded in a DISABLED state. You must enable before it can be triggered.**

---

### ReleaseNotes

Author.@JMichaelTX

**PURPOSE:**

* **Count the Number of Occurrences of a SubString within a String**

**REQUIRES:**

1. **KM 8.0.2+**
  * But it can be written in KM 7.3.1+
  * It is KM8 specific just because some of the Actions have changed to make things simpler, but equivalent Actions are available in KM 7.3.1.
.
2. **macOS 10.11.6 (El Capitan)**
  * KM 8 Requires Yosemite or later, so this macro will probably run on Yosemite, but I make no guarantees.  :wink: 

**NOTICE: This macro/script is just an _Example_**

* It has had very limited testing.
* You need to test further before using in a production environment.
* It does not have extensive error checking/handling.
* It may not be complete.  It is provided as an example to show you one approach to solving a problem.

**How To Use**

1. Make sure the data you want to use is properly set in the first two Actions (shown in magneta)
   * The StringToCount can be one or more characters, including blanks.
2. Trigger this macro.

**MACRO SETUP**

* **Carefully review the Release Notes and the Macro Actions**
  * Make sure you understand what the Macro will do.  
  * You are responsible for running the Macro, not me.  ??
.
1. Assign a Trigger to this maro..
2. Move this macro to a Macro Group that is only Active when you need this Macro.
3. ENABLE this Macro.
.
* **REVIEW/CHANGE THE FOLLOWING MACRO ACTIONS:**
(all shown in the magenta color)
   * Set variable SourceStr
   * Set Variable StringToCount

TAGS: @JXA @Strings

USER SETTINGS:

* Any Action in _magenta color_ is designed to be changed by end-user

ACTION COLOR CODES

* To facilitate the reading, customizing, and maintenance of this macro,
      key Actions are colored as follows:
* GREEN   -- Key Comments designed to highlight main sections of macro
* MAGENTA -- Actions designed to be customized by user
* YELLOW  -- Primary Actions (usually the main purpose of the macro)
* ORANGE  -- Actions that permanently destroy Variables or Clipboards,
OR IF/THEN and PAUSE Actions


**USE AT YOUR OWN RISK**

* While I have given this limited testing, and to the best of my knowledge will do no harm, I cannot guarantee it.
* If you have any doubts or questions:
  * **Ask first**
  * Turn on the KM Debugger from the KM Status Menu, and step through the macro, making sure you understand what it is doing with each Action.

---

![image|564x1211](upload://63KdukEmx8UxpFdI3909UIeU6Pd.jpg)

---

### JXA Script
```javascript
'use strict';  
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

(function myMain() {    // ~~~ automatically executed when this script is executed ~~~
  
var ptyScriptName   = "Count Number of String Occurrences"
var ptyScriptVer     = "1.0"
var ptyScriptDate   = "2018-05-26"
var ptyScriptAuthor = "JMichaelTX"
/*

PURPOSE: Count the Number of Occurrences of a SubString within a String

RETURNS: | integer | Count of Occurrences

KM VARIABALES REQUIRED:
• Local__SourceStr
• Local__StringToCount

KM VARIABLES SET:
• NONE

REF:

  1. cvc8445, 2018-05-23, Count of specific character (e.g. # of commas) in a Variable's content?
    Count of specific character (e.g. # of commas) in a Variable's content?
*/
  
  // --- SET CURRENT APP VARIABLE NEEDED FOR DIALOGS & StandardAdditions.osax ---
  var app = Application.currentApplication()
  app.includeStandardAdditions = true

  //--- GET THE DATA FROM KM MACRO ---
  
  var kme = Application("Keyboard Maestro Engine");
  
  var kmInst = app.systemAttribute("KMINSTANCE");
  var kmeApp = Application("Keyboard Maestro Engine")
   
  var sourceStr  = kmeApp.getvariable("Local__SourceStr",  {instance: kmInst}) || "aaa XYZ bbb XYZ ccc XYZ ddd";
  var strToCount = kmeApp.getvariable("Local__StringToCount",  {instance: kmInst}) || "XYZ";
  
  //--- COUNT THE NUMBER OF OCCURRENCES ---
  var numOccur = sourceStr.split(strToCount).length - 1
    
  return numOccur

})();  // ~~~ function run() is automatically executed when this script is executed ~~~


```

---

Side note to @peternlewis: I finally found a good use for “smart quotes”, in my KM Display window.  :wink:
3 Likes