Power Automate Tips: Use Substring to Fix Text and Automate Workflows

Learn how to use Power Automate substring function to extract text, clean data, and optimize workflows. Step-by-step examples, tips, and best practices included.

Contact Us
Let AI Summarize This Post for You
Table of Contents

    Have you ever struggled with extracting specific parts of text in your Power Automate flows? Maybe you need to grab the first few characters from an email subject, pull out a reference number from a long string, or clean up messy data before processing it.

    You're not alone. Text manipulation is one of the most common challenges in workflow automation, and that's exactly where the substring function becomes your best friend.

    In this comprehensive guide, you'll learn everything about using substrings in Power Automate - from basic extraction to advanced techniques that'll save you hours of manual work. Whether you're building your first flow or optimizing existing workflows, this article will show you practical solutions that actually work.

    What you'll discover:

    • How substring works and when to use them
    • Step-by-step examples with real code
    • Complete Power Automate string operations reference
    • Advanced techniques for complex scenarios
    • Error handling to prevent flow failures
    • Performance optimization tips
    • Troubleshooting common issues

    Let's dive in and transform how you handle text in your automation workflows.

    Understanding Substring Fundamentals

    What Is a Substring?

    The substring function extracts a portion of text from a larger string. Think of it like using scissors to cut out exactly the part you need from a piece of paper - no more, no less.

    Basic Syntax:

    substring(text, startIndex, length) 
    

    Parameters Explained:

    • text: The original string you want to extract from
    • startIndex: Where to start cutting (remember: counting starts at 0, not 1!)
    • length: How many characters to grab

    Simple Example to Get Started

    Let's say you have an order number like "ORD-2025-12345" and you only need the year "2025".

    substring('ORD-2025-12345', 4, 4) 
    

    Why it works:

    • Position 4 is where "2" starts (O=0, R=1, D=2, -=3, 2=4)
    • We grab 4 characters: 2, 0, 2, 5

    Real-World Use Cases with Complete Solutions

    Use Case 1: Extracting Email Domains

    Scenario: You receive customer emails and need to identify which company they're from.

    The Challenge: Email addresses like "johndoe@techimplement.com" - you need just "techimplement.com"

    Solution:

    substring(
      variables('email'),
      add(indexOf(variables('email'), '@'), 1),
      sub(length(variables('email')), 
    add(indexOf(variables('email'), '@'), 1))
    )
    

    What's happening here:

    • indexOf finds where the @ symbol sits
    • add(..., 1) moves one position forward (past the @)
    • Sub calculates the remaining characters
    • substring extracts everything after @

    Use Case 2: Processing Invoice Numbers

    Scenario

    Your invoices follow the format "INV-2025-MARCH-001" but you only need the month.

    Solution

    substring('INV-2025-MARCH-001', 9, 5) 
    

    Pro Tip: For variable positions, combine with indexOf to find the dash positions dynamically.

    Use Case 3: Cleaning Phone Numbers

    Scenario

    Phone numbers come in as "(555) 123-4567" but your system at TechImplement needs "5551234567"

    Solution with Function Combination

    replace(replace(replace(variables('phone'), '(', ''), ')', ''), '-', '') 
    

    Then extract specific parts

    substring(variables('cleanPhone'), 0, 3)  // Area code 
    

    Use Case 4: Extracting Date Components

    Scenario

    Date string "2025-12-15" needs to be split into year, month, and day.

    Complete Solution

    Year: substring('2025-12-15', 0, 4)
    Month: substring('2025-12-15', 5, 2)
    Day: substring('2025-12-15', 8, 2)
    

    Use Case 5: Processing Customer Reference Codes

    Scenario

    Reference codes like "CUST-GOLD-2025-A123" need category extraction.

    Solution

    Category: substring('CUST-GOLD-2025-A123', 5, 4)
    Year: substring('CUST-GOLD-2025-A123', 10, 4)
    Code: substring('CUST-GOLD-2025-A123', 15, 4)
    

    Complete Power Automate String Operations Reference

    Beyond substring, Power Automate provides a complete toolkit of string operations for text manipulation. Here's your comprehensive reference guide to all available string functions:

    String Extraction Functions

    SUBSTRING([string],[start],[count])

    • Returns a substring from the specified start position and number of characters
    • Parameters: string (STRING), start (INT), count (INT)
    • Output: STRING
    • Example: SUBSTRING('HelloWorld', 0, 5) returns "Hello"

    LEFT([string],[count])

    • Extracts characters from the left side of text
    • Parameters: string (STRING), count (INT)
    • Output: STRING
    • Example: LEFT('TechImplement-2025', 13) returns "TechImplement"

    RIGHT([string],[count])

    • Extracts characters from the right side of text
    • Parameters: string (STRING), count (INT)
    • Output: STRING
    • Example: RIGHT('INV-001234', 6) returns "001234"

    String Validation Functions

    CONTAINS([string],[value])

    • Returns TRUE if the string contains the value
    • Parameters: string (STRING), value (STRING)
    • Output: BOOL
    • Example: Check if email contains "@techimplement.com"

    STARTSWITH([string],[value])

    • Returns TRUE if string starts with the value
    • Parameters: string (STRING), value (STRING)
    • Output: BOOL
    • Example: Validate order numbers starting with "ORD-"

    ENDSWITH([string],[value])

    • Returns TRUE if string ends with the value
    • Parameters: string (STRING), value (STRING)
    • Output: BOOL
    • Example: Check file extensions like ".pdf"

    String Transformation Functions

    UPPER([string])

    • Converts text to uppercase
    • Parameters: string (STRING)
    • Output: STRING
    • Example: UPPER('techimplement') returns "TECHIMPLEMENT"

    LOWER([string])

    • Converts text to lowercase
    • Parameters: string (STRING)
    • Output: STRING
    • Example: LOWER('INVOICE') returns "invoice"

    TRIM([string])

    • Removes whitespace from both ends
    • Parameters: string (STRING)
    • Output: STRING
    • Example: TRIM(' data ') returns "data"

    LTRIM([string])

    • Removes whitespace from the beginning
    • Parameters: string (STRING)
    • Output: STRING

    RTRIM([string])

    • Removes whitespace from the end
    • Parameters: string (STRING)
    • Output: STRING

    String Utility Functions

    LEN([string])

    • Returns the length of the string
    • Parameters: string (STRING)
    • Output: INT
    • Example: LEN('Power Automate') returns 14

    CONCAT([string1],...,[stringN])

    • Joins multiple strings together
    • Parameters: string1...stringN (STRING)
    • Output: STRING
    • Example: CONCAT('Hello', ' ', 'World') returns "Hello World"

    Type Conversion Functions

    TOINT([string],[default])

    • Converts string to integer
    • Returns 0 or default value if conversion fails
    • Parameters: string (STRING), default (INT, FLOAT - optional)
    • Output: INT
    • Example: TOINT('123', 0) returns 123

    TOSTRING Functions

    • Convert various data types to string with optional formatting

    TOSTRING([int],[format]*)

    • Converts integer to string
    • Example: TOSTRING(1234, 'N0') returns "1,234"

    TOSTRING([float],[format]*)

    • Converts float to string with formatting

    TOSTRING([bool])

    • Converts boolean to "True" or "False"

    TOSTRING([date],[format]*)

    • Converts date to string with custom format

    TOSTRING([time],[format]*)

    • Converts time to string with custom format

    Advanced Techniques and Patterns

    Technique 1: Dynamic Length Extraction

    When you don't know exact positions, calculate them on the fly:

    substring(
      variables('text'),
      add(indexOf(variables('text'), '['), 1),
      sub(
        indexOf(variables('text'), ']'),
        add(indexOf(variables('text'), '['), 1)
      )
    )
    

    This grabs everything between square brackets, no matter where they are.

    Technique 2: Extracting Last N Characters

    Getting the last 4 digits of a credit card:

    substring(
      variables('cardNumber'),
      sub(length(variables('cardNumber')), 4),
      4
    )
    

    Technique 3: Middle Section Extraction

    Grabbing text between two delimiters:

    substring(
      variables('text'),
      add(indexOf(variables('text'), 'START'), 5),
      sub(
        indexOf(variables('text'), 'END'),
        add(indexOf(variables('text'), 'START'), 5)
      )
    )
    

    Technique 4: Conditional Substring

    Extract different portions based on conditions:

    if(
      greater(length(variables('text')), 10),
      substring(variables('text'), 0, 10),
      variables('text')
    )
    

    Error Handling and Validation

    Common Errors You'll Face

    Error 1: Index Out of Range

    Problem

    substring('Hello', 10, 5)  // Fails - starts beyond string length 
    

    Solution

    if(
    less(variables('startPos'), 
    length(variables('text'))),
    substring(variables('text'), 
    variables('startPos'), 
    variables('len')),
      ''
    )
    

    Solution with validation

    if(
        and(
            not(empty(variables('text'))),
            less(variables('startPos'), length(variables('text')))
        ),
        substring(
            variables('text'),
            variables('startPos'),
            min(variables('len'), sub(length(variables('text')), variables('startPos')))
        ),
        ''
    )
    

    Error 2: Null or Empty Strings

    Problem

    substring(variables('emptyText'), 0, 5)  // Fails on null 
    

    Solution with comprehensive checks

    if( 
    and( 
    not(empty(variables('text'))), 
    greater(length(variables('text')), 0), 
    greater(length(variables('text')), 
    variables('requiredLength')) 
    ), 
    substring(variables('text'), 0, 
    variables('requiredLength')),
    'DEFAULT_VALUE' 
    )
    

    Building Robust Error Handling

    Complete Validation Pattern

    if(
      and(
        not(empty(variables('input'))),
        greater(length(variables('input')), variables('requiredLength')),
        contains(variables('input'), variables('delimiter'))
      ),
      substring(variables('input'), variables('start'), variables('length')),
      'ERROR: Invalid input format.'
    )
    

    Function Combinations for Power Users

    Combination 1: Substring + Split

    Extract the domain from the email, then get the company name:

    first(split(
        substring(
            variables('email'),
            add(indexOf(variables('email'), '@'), 1),
            sub(length(variables('email')),
            add(indexOf(variables('email'), '@'), 1)
        ),
        '.'
    ))
    

    Combination 2: Substring + Replace + Trim

    Clean and extract:

    trim(replace(substring(variables('text'), 0, 10), '-', '')) 
    

    Combination 3: Substring + toLower/toUpper

    Standardize extracted text:

    toLower(substring(variables('code'), 0, 5)) 
    

    Troubleshooting Guide

    Issue 1: Getting Wrong Characters

    Problem

    Extracted text doesn't match expectations

    Solution

    • Remember indexing starts at 0
    • Count positions manually first
    • Use length() to verify string size
    • Test with known examples

    Issue 2: Flow Fails Intermittently

    Problem

    Works sometimes, fails other times.

    Solution

    • Add length validation before the substring
    • Check for null/empty values
    • Verify data consistency from source
    • Implement try-catch patterns with conditions

    Issue 3: Special Characters Causing Issues

    Problem

    Extraction fails with special characters.

    Solution

    • Use indexOf to locate positions dynamically
    • Escape special characters properly
    • Consider using contains for validation
    • Test with edge cases

    Issue 4: Performance Slowdowns

    Problem

    Flow takes too long with substring operations

    Solution

    • Minimize nested functions
    • Use variables to store intermediate results
    • Avoid repeated substring calls on the same text
    • Process in batches when possible

    Best Practices

    Always Validate Input Length

    Check if text exists before extracting:

    if(
      greater(length(variables('text')), 10),
      substring(variables('text'), 0, 10),
      variables('text')
    )
    

    Use Meaningful Variable Names

    Bad

    substring(variables('x'), 0, 5) 
    

    Good

    substring(variables('customerEmail'), 0, 5) 
    

    Document Your Logic

    • Add descriptions to your actions
    • Explain why specific positions are used
    • Note expected input formats

    Test Edge Cases

    • Empty strings
    • Very long strings
    • Missing delimiters
    • Special characters

    Store Reusable Patterns

    • Create child flows for common extractions
    • Build a library of tested expressions
    • Share with your team

    Performance Optimization Tips

    Tip 1: Cache Calculated Values

    Inefficient

    substring(variables('text'), indexOf(variables('text'), '@'), 5)
    substring(variables('text'), indexOf(variables('text'), '@'), 3)
    

    Optimized

    Set variable 'atPosition' = indexOf(variables('text'), '@')
    substring(variables('text'), variables('atPosition'), 5)
    

    Tip 2: Minimize Nested Functions

    Instead of

    substring(trim(toLower(replace(variables('text'), '-', ''))), 0, 5) 
    

    Break it down

    Step 1: replace(variables('text'), '-', '')
    Step 2: toLower(variables('step1'))
    Step 3: trim(variables('step2'))
    Step 4: substring(variables('step3'), 0, 5)
    

    Tip 3: Use Parallel Processing

    • When extracting from multiple items, use parallel branches
    • Process arrays efficiently with Apply to each

    Conclusion

    Mastering substring and string operations in Power Automate is essential for effective text manipulation in your workflows. By understanding when to use each function and following best practices for validation and error handling, you'll build robust automation that handles any text processing challenge efficiently.

    Start implementing these techniques today and transform your text processing workflows!

    FAQs

    Can I use a substring with dynamic content from previous actions, or does it only work with static text?

    Yes, substring works perfectly with dynamic content from triggers and previous actions like email subjects, SharePoint items, or HTTP responses. Simply select the dynamic content in your flow where you'd normally use a variable, making it flexible for real-time data processing.

    What happens if my start position or length parameters are calculated values that might be negative or zero?

    Power Automate throws an error for negative start positions, so always validate calculated values with conditions first. Zero-length values return empty strings without failing, but it's best practice to ensure your calculations always produce positive numbers.

    Is there a maximum character limit for the text I can process with substring operations?

    Power Automate handles strings up to 100MB, but processing very large strings over 1MB can cause performance slowdowns and timeouts. For large text files, split the content into smaller chunks first or consider using Azure Functions for better performance.

    Can I chain multiple substring operations on the same text to extract several pieces at once?

    Chaining multiple substring operations is inefficient because it recalculates positions repeatedly. Instead, calculate all positions once and store them as variables, then reference those variables in separate substring calls for better performance.

    How do I handle situations where my delimiter might appear multiple times in the text?

    Use indexOf for the first occurrence and lastIndexOf for the last occurrence of any delimiter. For multiple occurrences in between, use the split function to create an array and access specific segments with array indexing.

    What's the difference between using substring and using split for text extraction?

    Substring is best for position-based extraction when you know exact character positions or counts. Split is ideal for delimiter-separated data where you need to extract segments between consistent separators like commas, dashes, or pipes.

    We Don't Do Consultations. We Solve Your Growth Challenges. Discuss Your Challenge
    Miley Johnson

    Our Growth Strategist will reach out within the same day to discuss your project.

    Grow Your Business Faster with AI, CRM, and Proven Digital Strategies

      Get In Touch With us

        Why TechImplement

        Enterprise-Grade Quality

        ISO-certified processes ensuring clean, scalable, and maintainable code on every project.

        Best Pricing

        Unlock unbeatable value with our competitive rates and cost-effective solutions.

        Agile and Transparent

        Stay informed every step of the way with our transparent processes.

        ISO 9001 Certified ISO 27001 Certified Microsoft Authorized Reseller Certified Intercom Partner ISO 9001 Certified ISO 27001 Certified Microsoft Authorized Reseller Certified Intercom Partner
        Phone Number Icon