具有深层对象替换问题的 JavaScript 正则表达式

发布于 2024-10-15 21:27:22 字数 567 浏览 2 评论 0原文

大家好,我正在编写的模板引擎代码进行字符串替换时遇到问题。如果我的代币深度为 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

黎夕旧梦 2024-10-22 21:27:22

请参阅 这个问题 关于花括号。也许您选择的浏览器不像 Chrome 那样理解?

See this SO question about curly braces. Perhaps your browser of choice isn't as understanding as chrome is?

甜尕妞 2024-10-22 21:27:22

您需要转义“.”作为 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文