Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace regex to array element in Javascript

I met with the following problem. I wanted to replace a tag on the name of the corresponding element of the array string. Maybe a little awkwardly explain it, so I will show you the code:

var test = [];
test['some'] = 'Some test';
var content = '{some}';
document.write(content.replace(/{([^}]+)}/g, test[RegExp.$1])); // It doesn't work
document.write(test[RegExp.$1]); // It work

Now my question: why the replace tag is not getting the string held in the test ['some'] (get undefined)? During the second attempt to get normal string 'Some test'. How to fix it to properly converted tags when converting?

like image 237
Jake Avatar asked Apr 21 '26 04:04

Jake


1 Answers

You need to escape { and } as they both are special regex symbols:

Use this regex:

/\{([^}]+)\}/g

EDIT: You need String#replace with custom function handler:

repl = content.replace(/\{([^}]+)\}/g, function($0, $1) {return test[$1];});
like image 130
anubhava Avatar answered Apr 23 '26 16:04

anubhava



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!