Replace all the instances of a character

0 4 1,206

There are many scenarios when we need to replace a special character in a file for all of its instances. But Apigee replace all in javascript policy doesn't work as expected.

I found Apigee python script much helpful and easy in this case. You can use replace method of python which will replace all of the instances.

Hope this will help many developers.

Comments
kurtkanaskie
Staff

I've just tested a simple example using Message Template and it works if I use single quotes in the Template expression.

<AssignMessage name="AM-ReplaceAllHeader">
    <DisplayName>AM-ReplaceAllHeader</DisplayName>
    <AssignVariable>
        <Name>message.header.replaceall</Name>
        <Template>{replaceAll(message.header.replaceall, 'X', 'x')}</Template>
    </AssignVariable>
    <IgnoreUnresolvedVariables>true</IgnoreUnresolvedVariables>
</AssignMessage>

The request below shows the response replacing all 'X' with 'x'.

$ curl -i https://ORG-ENV.apigee.net/features/v1/replaceall-header -H "replaceall:1234X5678X90XX-XX"
HTTP/1.1 200 OK
Date: Tue, 05 Jan 2021 14:47:00 GMT
Content-Length: 0
Connection: keep-alive
Host: ORG-ENV.apigee.net
X-Forwarded-For: 64.121.12.38
X-Forwarded-Port: 443
X-Forwarded-Proto: https
User-Agent: curl/7.64.1
Accept: */*
replaceall: 1234x5678x90xx-xx<br>

It doesn't work if I use the double quote character in the expression:

<Template>{replaceAll(message.header.replaceall, "X", 'x')}</Template>
Not applicable
Did you try with special characters? I am replacing the special characters in some scenarios.
In general I felt the python policy worked in all scenarios.
dchiesa1
Staff

have you got an example of the special characters that don't work?

namitgarg1991
Bronze 1
Bronze 1

Hi, replaceAll function is not working for me when i am using special charaters. 

<Template>{replace(userValidationServiceCalloutResponse.content,’(‘,’‘)}</Template>

Version history
Last update:
‎12-28-2020 07:35 AM
Updated by: