Function to replace first phone number and return list separate by comma

Case 1: I have a phone number like this:
Phone
0912345670
I want to replace first number 0 by 84 and return new number like this 84912345670

Case 2: I have a list of phone number like this:
Phone
0912345670
0912345671
0912345672

I want to replace first number 0 by 84 and return list separate by comma like this: 84912345670,84912345671,84912345672 (not have blank).

I think Function Node can help but I have a little knowledge about code, can you help me?

Hey @huuich!

You can use the .replace() JavaScript method to replace the 0 with 84. The expression might look like something similar to this: {{$json["number"].replace('0','84')}}.

For Case 2, can you please share how does the data structure look like? Are the numbers returned as a single item, or are they returned as multiple different items?

1 Like

@harshil1712 Thanks for quick reply, could you send me a working workflow with case 1?

Sure. Here’s the example

{
  "nodes": [
    {
      "parameters": {
        "values": {
          "string": [
            {
              "name": "Number",
              "value": "0912345670"
            }
          ]
        },
        "options": {}
      },
      "name": "Set",
      "type": "n8n-nodes-base.set",
      "typeVersion": 1,
      "position": [
        450,
        300
      ]
    },
    {
      "parameters": {
        "keepOnlySet": true,
        "values": {
          "string": [
            {
              "name": "format_number",
              "value": "={{$json[\"Number\"].replace('0','84')}}"
            }
          ]
        },
        "options": {}
      },
      "name": "Formatted Number",
      "type": "n8n-nodes-base.set",
      "typeVersion": 1,
      "position": [
        650,
        300
      ]
    }
  ],
  "connections": {
    "Set": {
      "main": [
        [
          {
            "node": "Formatted Number",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  }
}
1 Like

@harshil1712 Thanks for your clearly example, it’s simple but powerful and almost solve both case 1 and 2 for me. And my data like this

image

If use your code, only Number (mobile) show on result, I want to show all data on result, too. Could you give an example to do this?

In the Format Number node (Set node) toggle Keep Only Set to false. This will return the data from the previous node as well. When it is set to false it will return firstname, mobile, updated, as well as the formatted number.

1 Like

That’s ok for the solution and not need to use case 2. Thank you so much!

1 Like

I am happy that it solves your issue! Have fun! :slightly_smiling_face:

1 Like