This is similar to your code, but I would suspect it will more correct, because your code will substitute the blank characters within the text.
txt = " Scripting Guide";
numLeadingBlanks = Length( txt ) - Length( Trim( txt ) );
It can also return an error if there are trailing blanks.
This should correct for that issue
txt = " Scripting Guide ";
numLeadingBlanks = Contains( txt, Substr( Trim( txt ), 1, 1 ) ) - 1;
Jim