How to replace string in 2nd occurrence

Describe the problem/error/question

How do I replace a string in the 2nd occurrence? lets say for example I want to replace the 2nd [/CODE]. How can I do this cause my workflow is replacing the 1st occurrence which I don’t want

What is the error message (if any)?

Please share your workflow

Share the output returned by the last node

Information on your n8n setup

  • **n8n version:**1.81.4
  • **Database (default: SQLite):**default
  • **n8n EXECUTIONS_PROCESS setting (default: own, main):**default
  • **Running n8n via (Docker, npm, n8n cloud, desktop app):**npm
  • **Operating system:**WIndows Server 2022

I think you’ll need to write your own parsing function to extract the data within the brackets [ ]

Here’s a solution for your case: it essentially parses all tags and their nested tags, allowing you to effectively create an ETL node

If you want something simple, and you know you will never have more than 2 occurences of “[/CODE]”, this would do it.

{{ $json.data.replace(/\[\/CODE\]/g, (match,offset) => offset > $json.data.indexOf('[/CODE]') ? 'Link5\n[/CODE]' : match) }}

Reference: String.prototype.replace() - JavaScript | MDN

Explanation:

  1. The “match” string is a regex, so all special characters must be escaped (so \[\/CODE\] instead of [/CODE]
  2. The replacement is a function instead of a static string. The function uses the match and offset parameters. The function body is: offset > $json.data.indexOf('[/CODE]') ? 'Link5\n[/CODE]' : match
    • This chooses (ternary / ? operator) based on whether the current offset is past the first occurrence indexOf() of [/CODE] (so it would change ANY match after the first one)
      • true (ternary arg before :) → replace with specified text → 'Link5\n[/CODE]'
        • Note: This value could be assembled from expression references. e.g. $json.newLink + '\n[/CODE]'
      • false (ternary arg after :) → just re-insert the value of match
    • Note: There are no groupings in the regex, so there are no p0, p1, ... parameters positioned between the match and offset parameters.

How do I call an expression within expression?
{{ $json.data.replace(/\[\/CODE\]/g, (match,offset) => offset > $json.data.indexOf('[/CODE]') ? '{{ $json.link }}Link5\n[/CODE]' : match) }}

I’m getting invalid syntax error

It should work if you remove the inner {{ }}, and be sure the $json.link part is not within quotes.

{{ $json.data.replace(/\[\/CODE\]/g, (match,offset) => offset > $json.data.indexOf('[/CODE]') ? $json.link + '\n[/CODE]' : match) }}

Remember to mark the answer that solved your issue as the solution.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.