Templater Promote Note Find-Replace Snippet

Hey all, I wrote the following templater snippet to “promote” my notes by finding a status indicator and replacing it with the next stage status indicator.

Here is the snippet:

<%* 
var file = app.workspace.getActiveFile()
var t = await app.vault.read(file)
var s = t.replace("STAGE-1", "STAGE-2").replace("STAGE-2", "STAGE-3").replace("STAGE-3", "STAGE-4")
app.vault.modify(file, s)
%>

So If I have a note that includes the text “STAGE-1”, running this template on it will change the text to “STAGE-2”. Running it again will change it to “STAGE-3”, etc. (more levels can by added by repeating .replace("STAGE-N", "STAGE-N+1") at the end).

In general, you can use this snippet for any series of text replacement operations.

7 Likes

Brilliant. This is what tag-cycle in Roam used to do.

Thanks for your example, I have tried it and if the note has stage-1, it goes to Stage-4.
I guess it passes quickly by 2, 3 and 4.

I have understood it badly? Or in the example of the status you write, you should only make the replacement once.

Is it possible that only do it once?

1 Like

In case someone else stumbles upon this, it should work backwards.
So Stage 3 should be promoted to Stage 4 before Stage 2 gets promoted to Stage 3:

<%* 
var file = app.workspace.getActiveFile()
var t = await app.vault.read(file)
var s = t.replace("STAGE-3", "STAGE-4").replace("STAGE-2", "STAGE-3").replace("STAGE-1", "STAGE-2")

app.vault.modify(file, s)
%>

.replaceAll to do all instances instead of sequentially.

2 Likes

One more addition: When I tried this, it always added a blank line where my cursor was. Using whitespace control solved this.

So if using the example from above:

<%* 
var file = app.workspace.getActiveFile()
var t = await app.vault.read(file)
var s = t.replace("STAGE-3", "STAGE-4").replace("STAGE-2", "STAGE-3").replace("STAGE-1", "STAGE-2")

app.vault.modify(file, s)
-%>

Hi this looks cool. Would something similar be used for replacing spaces (" ") in a file name with underscores and paste in the document body?
I looked at the templater document for an out of the box solution, but I don’t see one.
Thanks!