Replacing text in Dropbox link

Hi, I’m new to scripting. I’m trying to make an action that replaces text at the end of a Dropbox link in the current draft.

Using this script I can replace text using the location (argument?) but only counting from the start of the link. I thought I could use a minus number to count back from the end, but this doesn’t work. Any help would be appreciated.

var text = editor.getSelectedText(); editor.setTextInRange("10","6","_text_");
1 Like

Could you give an example of a text you are trying to change, and what it should look like after the change? I’m having trouble envisioning the big picture here.

I want to change the end of a Dropbox link to an image in order to turn it into a URL link for a blogpost. An example link might be //https://www.dropbox.com/s/tq0zyaxzx0pd/201634567.jpeg?dl=0

I need to replace ‘dl=0’ with ‘raw=1’ so that the link displays as an image, so that’s my goal here.

Try putting this line in your script. It uses a regular expression to match the parameters globally through the draft content and replaces it with the raw parameter specified.

draft.content = draft.content.replace(/\?dl=0/g, "?raw=1");

Can that same construct work with variables? For example, could the variables:

oldExtension
newExtension

be used in the replace method?

That did the trick - thank you! I hadn’t looked at draft objects in the scripting reference.

You could do it with the editor object too, including everything or just the selection, but I figured it would be most efficient to do the whole draft at once, and this general approach is more broadly applicable in that you can run it on multiple drafts without needing to load each into the editor to process it.

With some modification, yes, you would need to prime a regular expression object with the search string and use that for the find component.

but, this isn’t the first time I’ve forgotten about a newer JavaScript function that solves everything more easily. Using a regular expression for a global replace is now an old technique, and this isn’t the first time the existence of the replaceAll() function has slipped my mind.

This should prove to be an altogether simpler state of affairs.

let oldExtension = "?dl=0";
let newExtension = "?raw=1";
draft.content = draft.content.replaceAll(oldExtension, newExtension);

No need for regular expressions.

1 Like

Thanks! Definitely simplifies things. Is there a reference that I should have used to find the ReplaceAll method myself?

I just use Google. There are references, but unless you know what you are looking for by name, a web search will always win out.

This all helpful stuff - thank you.