How to apply escape characters to the individual string in the string variable

Krzysztof Nowicki 61 Reputation points
2025-02-26T11:55:49.6566667+00:00

String variable content is dynamic and the parameters may change which means I cannot use json compose and apply replace function. I need to search for the specified string value eg. Special_Instructions and apply escape characters to " as \\" and new lines as \n.

Screenshot 2025-02-26 114956

What would be the best approach here?

Azure Logic Apps
Azure Logic Apps
An Azure service that automates the access and use of data across clouds without writing code.
3,369 questions
{count} votes

Accepted answer
  1. RithwikBojja 240 Reputation points Microsoft Vendor
    2025-02-26T17:35:50.6433333+00:00

    Hi @Krzysztof Nowicki,

    Below is the design which does the ask:

    Firstly, I had set the string variable as below:

    enter image description here

    Then in JavaScript Action, used below code:

    
    function rithreplacefunc(jsonString) {
    
        const ri_match = jsonString.match(/"Special_Instructions"\s*:\s*"(.*?)"(\s*,\s*"\w+":)/s);
    
        
    
        if (ri_match) {
    
            let gotVal = ri_match[1]; 
    
            let choVal = gotVal.replace(/"/g, '\\"');
    
    let evalue = choVal.replace(/\n/g, '\\n')
    
            return jsonString.replace(ri_match[0], `"Special_Instructions": "${evalue}"${ri_match[2]}`);
    
        }
    
        throw new Error("Hello Rithwik, Special_Instructions property not found in the given JSON string.");
    
    }
    
    let cho_ri_data = workflowContext.actions.Set_variable.inputs.value;
    
    if (!cho_ri_data || typeof cho_ri_data !== "string") {
    
        throw new Error("Hello Rithwik, Set_variable.inputs.value is undefined, incorrect, or not a JSON string.");
    
    }
    
    let riout = rithreplacefunc(cho_ri_data);
    
    return riout;
    
    

    enter image description here

    Output:

    enter image description here

    Hope this helps.

    If the answer is helpful, please click Accept Answer and kindly upvote it. If you have any further questions about this answer, please click Comment.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.