Javascript - replace string between brackets, but the brackets should stay

Use zero width assertions instead of actually matching the brackets.

EDIT: Javascript does not have lookbehind. :c

As a general solution, you could capture the surrounding content and put it back in the replacement string using backreferences.

str.replace(/(\[).+?(\])/g, "$13$2")

Alternatively, you could include hardcoded brackets in your replacement.


Do you need something more than below?

 var num=2 // parse this from drafts [2]
 num++;
 var newstr=str.replace(/\[(.+?)\]/g, "["+num+"]")

Or the brackets can change to <> {} per input?

You can also give a function instead of the replace-string.

var str = "Drafts [2]";

function replacer(match, p1, p2, p3, offset, string) {
  return p1 + (1+parseInt(p2)) + p3;
}
var newstr=str.replace(/([\[(])(.+?)([\])])/g, replacer);
alert(newstr); // alerts "Drafts [3]"

If you need such functionality more then once you may create function with method borrowing trick.

const args = {
    source: "Lorem [ipsum] dolor [sit] amet",
    prefix: `<i style="background-color:yellow">`,
    suffix: '</i>',
    global: true,
    deleteBrackets: true
}

const bracketsToTags = (args) => {
    const { source, prefix, suffix, global = true, deleteBrackets = false } = args;
    const reg = /\[(.+?)\]/;
    source.replace = ''.replace;
    return source.replace(new RegExp(reg, global ? 'g': ''), 
                             (withBrackets, withoutBrackets) => (
        `${prefix}${deleteBrackets ? withoutBrackets: withBrackets}${suffix}`
    ))
}

So, running function

bracketsToTags(args)

you'll get

"Lorem <i style="background-color:yellow">ipsum</i> dolor <i style="background-color:yellow">sit</i> amet"

PS: use 'React HTML Parser' for React - link


You could just add the brackets to the replacement text like this:

str.replace(/\[(.+?)\]/g, "["+3+"]")

Edit: If you need to do anything with the number in the brackets, you can use a function instead of the replacement text:

str.replace(/\[(.+?)\]/g, function(string, first){
  // string is the full result of the regex "[2]"
  //first is the number 2 from "draft [2]"
  return "["+(first++)+"]";
})