Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question
add comment

2 Answers

up vote 1 down vote accepted

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];});
share|improve this answer
    
Thanks for the reply, but unfortunately it still does not work. I've tried both document.write(content.replace(/\{([^}]+)\}/g, test[RegExp.$1])); and document.write(content.replace(/\{([^}]+)\}/g, test["$1"])); –  Unstoppable 2 days ago
    
check updated answer. –  anubhava 2 days ago
    
It works perfectly! Thank you. –  Unstoppable 2 days ago
    
You're welcome, glad it worked out. –  anubhava 2 days ago
add comment

Check this demo jsFiddle

JavaScript

var test = [];
test['some'] = 'Some test';
var content = '{some}';
document.write(content.replace(new RegExp('/{([^}]+)}/','g'), test['some'])); 
document.write(test['some']);

Result

{some}Some test

Here i check your regexp work perfect Hope this help you!

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.