Question

var string = input.replace(/\[noparse\]([^\]]+)?\[\/noparse\]/ig, '<noparse>'+removeBrackets('$1')+'</noparse>');

This expression should be taking a string and encoding the parts wrapped in [noparse] tags so they don't render in a textarea.

I tested this as:

var string = input.replace(/\[noparse\]([^\]]+)?\[\/noparse\]/ig, '<noparse>test</noparse>');

and:

var string = input.replace(/\[noparse\]([^\]]+)?\[\/noparse\]/ig, '<noparse>'+String('$1')+'</noparse>');

and they work (without the desired effect).

function removeBrackets(input){
return input
.replace(/\[/g, '&#91;')
.replace(/\]/g, '&#92;');
}

What am I doing wrong in trying to pass the back reference into the removeBrackets function?

Was it helpful?

Solution

replace takes a function as callback and passes the capturing groups in the arguments:

var regex = /\[noparse\]([^\]]+)?\[\/noparse\]/ig;

string = string.replace(regex, function(_, match) {
  return '<tag>'+ removeBrackets(match) +'</tag>';
});

The first param _ is the full string, unnecessary in most cases.

OTHER TIPS

Your regular expression won't work, because of an error in the negative character set you're using. This fixes it:

input.replace(/\[noparse\]([^\[]+)?\[\/noparse\]/ig, '<noparse>test</noparse>');
                              ^

Then, to perform the actual replacement, you need to pass a function as the second argument to .replace() instead of a simple string.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top