Forum Discussion

bklabel1's avatar
bklabel1
Occasional Contributor
4 years ago

Formatting data in a request

My phone number is coming from an expanded expression in the format of 333-333-1234.  I want to change it to (333)-333-1234 before using it in the POST.

 

I'm looking in documentation but I do not see how to do this.

 

Thanks,

Kevin

  • bklabel1 : There is no straight way to do this, you can achieve this by writing your groovy code.

     

    You can use below code if input format will be as mentioned in question

     

    def r = '333-333-1234'
    
    def with_braces =  '(' + r.split('-')[0] + ')'
    
    desired_num = with_braces +'-'+ r.split('-')[1] +'-'+ r.split('-')[2]
    
    log.info desired_num
  • bklabel1 : There is no straight way to do this, you can achieve this by writing your groovy code.

     

    You can use below code if input format will be as mentioned in question

     

    def r = '333-333-1234'
    
    def with_braces =  '(' + r.split('-')[0] + ')'
    
    desired_num = with_braces +'-'+ r.split('-')[1] +'-'+ r.split('-')[2]
    
    log.info desired_num
  • ChrisAdams's avatar
    ChrisAdams
    Champion Level 3

    Hi,

    You could used a Groovy Script test step to format the value prior to your API request step.  Then, in your API request step, you can 'pull in' this formatted value.

     

    Example script...

    def number = '333-333-1234'
    
    def firstHyphen = number.indexOf("-");
    
    log.info("Insert a closed bracket at pos " + firstHyphen);
    
    def formattedNumber = number.substring(0, firstHyphen) + ")" + number.substring(firstHyphen);
    
    formattedNumber = "(" + formattedNumber;
    
    return formattedNumber;
    • bklabel1's avatar
      bklabel1
      Occasional Contributor

      Himanshu,

      I appreciate your explanation and sample of groovy code which is new to me.

      Thanks,

      Kevin