[英]How to replace regex to array element in Javascript
我遇到了以下问题。 我想替换数组字符串的相应元素名称上的标记。 也许有点尴尬地解释它,所以我会告诉你代码:
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
现在我的问题是:为什么替换标签没有得到测试['some']中的字符串(得到未定义)? 在第二次尝试获得正常字符串'一些测试'。 如何在转换时将其修复为正确转换的标签?
您需要转义{ and }
因为它们都是特殊的正则表达式符号:
使用这个正则表达式:
/\{([^}]+)\}/g
编辑:你需要String#replace
与自定义函数处理程序:
repl = content.replace(/\{([^}]+)\}/g, function($0, $1) {return test[$1];});
查看此演示jsFiddle
var test = [];
test['some'] = 'Some test';
var content = '{some}';
document.write(content.replace(new RegExp('/{([^}]+)}/','g'), test['some']));
document.write(test['some']);
{some}Some test
在这里,我检查你的正则表达式工作完美希望这对你有所帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.