简体   繁体   English

如何在Javascript中将正则表达式替换为数组元素

[英]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)? 现在我的问题是:为什么替换标签没有得到测试['some']中的字符串(得到未定义)? During the second attempt to get normal string 'Some test'. 在第二次尝试获得正常字符串'一些测试'。 How to fix it to properly converted tags when converting? 如何在转换时将其修复为正确转换的标签?

You need to escape { and } as they both are special regex symbols: 您需要转义{ and }因为它们都是特殊的正则表达式符号:

Use this regex: 使用这个正则表达式:

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

EDIT: You need String#replace with custom function handler: 编辑:你需要String#replace与自定义函数处理程序:

repl = content.replace(/\{([^}]+)\}/g, function($0, $1) {return test[$1];});

Check this demo jsFiddle 查看此演示jsFiddle

JavaScript 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! 在这里,我检查你的正则表达式工作完美希望这对你有所帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM