How Do I Get the Position of a Character in a String using KM Actions?

Thanks for the suggestion, Chris.

But I really don't like either of our methods.
It looks like this just can't be done simply in KM Actions.

Of course, your script snippet is exactly what I had in mind:

tell application "Keyboard Maestro Engine" to set testSel to getvariable "testSel"
set subStringLength to offset of ";" in testSel

So, I gave up on non-script KM Actions, and wrote this script.
It takes the process through the next step of calculating the position of the END of the substring.

(*
==========================================================
  Get Position of End of Substring within Main String
==========================================================

RETURNS:
  • Position of End of StringToFind within MainString
  • 0 if StringToFind is NOT Found
  
VER:   1.0    LAST UPDATE:   2016-12-23

AUTHOR:    @JMichaelTX

Keyboard Maestro VARIABLES REQUIRED
  • SCPT__MainString -- string to be searched
  • SCPT__StringToFind -- sub-string to find within SCPT__MainString
  
REQUIRED:
  1.  Mac OS X Yosemite 10.10.5+
  2.  Keyboard Maestro 7.3+
==========================================================
*)

tell application "Keyboard Maestro Engine"
  set mainStr to getvariable "SCPT__MainString"
  set subStr to getvariable "SCPT__StringToFind"
end tell

if ((mainStr = "") or (subStr = "")) then
  error "ERROR:" & return & ¬
    "These KM Variables must be set and not empty:" & return & "SCPT__MainString" & return & "SCPT__StringToFind"
end if

### For Testing ###
--set mainStr to "1234;6789"
--set subStr to ";"

--- Get Start of StringToFind ---
set posSubStr to offset of subStr in mainStr

if (posSubStr > 0) then
  --- Add Length of StringToFind to Start Position ---
  set posSubStrEnd to posSubStr + (length of subStr) - 1
else
  set posSubStrEnd to 0
end if

return posSubStrEnd
1 Like