具有深层对象替换问题的 JavaScript 正则表达式
大家好,我正在编写的模板引擎代码进行字符串替换时遇到问题。如果我的代币深度为 1 级,则一切正常。示例 {someProperty}。但如果我尝试搜索嵌套对象,它永远不会进行替换。示例 {myobj.deep.test}。我已附上我正在使用的代码。感谢您的帮助!
function replaceStuff(content, fieldName, fieldValue) {
var regexstr = "{" + fieldName + "}";
console.log("regexstr: ", regexstr);
//var regex = new RegExp("{myobj\.deep\.test}", "g"); //this works as expected
var regex = new RegExp(regexstr, "g"); //this doesn't
return content.replace(regex, fieldValue);
}
replaceStuff("test: {myobj.deep.test}", "myobj.deep.test", "my value");
Hey all, having an issue doing string replacement for template engine code I am writing. If my tokens are 1 level deep everything works fine. Example {someProperty}. But if I try searching for a nested object it never does the replace. Example {myobj.deep.test}. I've attached the code I am playing around with. Thanks for the help!
function replaceStuff(content, fieldName, fieldValue) {
var regexstr = "{" + fieldName + "}";
console.log("regexstr: ", regexstr);
//var regex = new RegExp("{myobj\.deep\.test}", "g"); //this works as expected
var regex = new RegExp(regexstr, "g"); //this doesn't
return content.replace(regex, fieldValue);
}
replaceStuff("test: {myobj.deep.test}", "myobj.deep.test", "my value");
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
请参阅 这个问题 关于花括号。也许您选择的浏览器不像 Chrome 那样理解?
See this SO question about curly braces. Perhaps your browser of choice isn't as understanding as chrome is?
您需要转义“.”作为
fieldName
参数传入的字符串中的字符。对于您想要按字面解释的任何其他特殊正则表达式字符,也是如此。基本上,fieldName
被视为正则表达式模式的一部分。如果您不希望将
fieldName
计算为正则表达式代码,您可能需要考虑使用字符串操作来代替。编辑:我刚刚在 FireFox 中运行了您的代码,它运行得很好。您这里可能还有其他事情发生。
You need to escape the '.' characters in the string you're passing in as the
fieldName
parameter. Ditto for any other special regex characters that you want to be interpreted literally. Basically,fieldName
is being treated as part of a regex pattern.If you don't want
fieldName
to be evaluated as regex code, you might want to consider using string manipulation for this instead.Edit: I just ran your code in FireFox and it worked perfectly. You may have something else going on here.