Escaping Regex is not working

Hi everyone,

I am trying to create a regex on Drafts. The Regex is working on Regex101, but it seems that the escaping \ is not working properly on Drafts.

I need to get all the images with this formatting : ![[path/to/image]]

Here my script :

const regexp = RegExp('\!\[\[','gmi'); const images = regexp.exec(draft.content);

If i try a Regex without the escaping \ it’s working perfectly.

Thanks for your help,
Damien

EDIT: I don’t know why but with the RegExp you need to double escape \. But the same regex doesn’t work with draft.content.replace(‘Regex’, “”);

I really don’t understand the logic… I need to use the replace function too but the escaping seems different. Who could help me with this ?

Thanks

I just copied the text you posted and used it as string and assumed you want to extract the content in the brackets. (path/to/image)

when I run this script:

const regex = /\!\[\[(.*)\]\]/gmi;
const str = `I need to get all the images with this formatting : ![[path/to/image]]`;
const subst = `$1`;

// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);

alert("Substitution result: " + result);

the alert contains the expected result

I may be wrong, but here’s my take. Unlike regex101, which is a testing tool, here you are encoding the content into a string in code, so you are escaping the slash first, and then that escaped slash is then available to escape the bracket when the string is interpreted as it is parsed sequentially rather than as a group.

const regexp = RegExp('\\\[\\[.*?\\]\\]','gmi');
let images;
while ((images = regexp.exec(draft.content)) !== null)
{
	images.forEach(path => {alert(path)});
}
1 Like