change substring function to handle null values correctly