Remove text from a string

Hi,

I’m looking to manipulate a string of text which contains multiple labels like <ADDRESS> or <PERSON>. I’d normally do this with a regular expression in SQL or Python, but my javascript is weak / non-existent so I’m not quite sure how to approach this in n8n.

Imagine I had a string of text that read:

“Hello my name is <PERSON> and I live at <ADDRESS> with my partner <PERSON>.”

In SQL I would use the following function:

regexp_replace(replace(regexp_replace(redacted_comment,’<[^>]>|{{[^}]}}’,’**’,‘g’),’"’,’’),’\s+’,’ ',‘g’)

After manipulation the text would look like:

“Hello my name is ** and I live at ** with my partner **”"

I was hoping I’d be able to do this with an expression in a set node, but I’m guessing it might need a function node.

Any help gratefully received :slight_smile:

Regards
Scott

Hi @scottjscott

Regex like this is done with a replace. You can use normal javascript in n8n. So the url below will tell you what you need I guess.

1 Like

Thanks @BramKn.

With the little tutorial you attached I’ve hacked together a javascript function item which does the trick for me.

const reg1 = /<[^>]>|{{[^}]}}/g;
const reg2 = /\s+/g;
const str = ($json[“comments”]);
const newStr = str.replace(reg1, “**”);

const newStr2 = newStr.replace(reg2," ");

item.oldcomment = ($json[“comments”]);
item.newcomment = newStr2;
return [item.oldcomment, item.newcomment]

Thanks for the tip.

Scott

2 Likes

I’ve made this a little simpler still by doing the following within an expression in a set node:

{{$json[“comments”].replace(/<[^>]>|{{[^}]}}/g,"**")}}

This is just applying the first regex from the function item (replaces all strings that are within angle brackets e.g. <ADDRESS> or double curly braces e.g. {{ADDRESS}}).

3 Likes