JS: regex capture won’t convert to number (solved)

Given a draft with content


This code works as expected:

draft.content = draft.content.replace(/([0-9])/, "$1"+6);

It returns


However this code

draft.content = draft.content.replace(/([0-9])/, Number("$1")+6);



I checked and Number(“1”) returns 1 as expected.

Why does the captured group in my regex, which is the string 1 as evident in the first example, not convert to the number 1 in the second?

I have been puzzled by this for hours, and have also tried parseInt and parseFloat with the same result.

Is this a bug? Or am I missing something?

It’s the replace function that substitutes the captured subgroup for the token $1. The Number constructor has no idea what to do with it. Do a RegExp.match instead of a String.replace to pull out the actual captured value, then you can parseInt it or whatever to get an integer to work with.

Ok this works

var r =/[0-9]+/;
var n = draft.content.match(r);
draft.content = Number(n)+6;

Now I just need to make that work through every line of the draft.

And done in context:

// Clean up Highlights markdown

var d = draft.content.replace(/\(highlights.*\)/g,"()");

var p = Prompt.create();
p.title="Enter page offset";
p.addTextField("offset", "", "");
if (p.show()) {
 var offset = p.fieldValues["offset"];
}  else {

var pr=/\[Page\ (\d+)\]/

const l = d.split("\n").reduce(
            // Accumulator updated with every line.
            (a, line) => pr.test(line) ? {
                body: a.body.concat("[Page "+(Number(line.match(pr)[1])+Number(offset))+"]")
            } : {
                body: a.body.concat(line),

            // Seed value of accumulator.
                body: [],

draft.content = l.body.join('\n');;
1 Like

This looks suspiciously like an answer to a task I am trying to automate in Drafts: the cleanup of annotation text sent from iAnnotate PDF reader. Care to share more about your setup here? I don’t have a good enough RegEx expertise to accomplish what I want, and your page offset here looks like more than I could have hoped for.