【问题标题】:replacing regex at nth position only not working仅在第 n 个位置替换正则表达式不起作用
【发布时间】:2017-06-15 02:56:22
【问题描述】:

我的文字是

<DIV STYLE="text-align:Left;font-family:Segoe UI;font-style:normal;font-weight:normal;font-size:12;color:#000000;"><P STYLE="font-family:Arial;margin:0 0 0 0;"><SPAN STYLE="font-family:Segoe UI;"><SPAN>{firstname} will continue to learn high frequency words, try to remember words and us them in their writing. {firstname} always uses correct spacing in their writing and attempts to use punctuation.</SPAN></SPAN></P></DIV>

所以现在我想用 {firstname_C}

替换索引 202 处的 {firstname}

我的代码在这里不起作用

var endIndex = 202;
var pattern = new RegExp("({firstname}{" + endIndex + "})", "g");
                commentString = commentString.replace("({firstname})/g", "{firstname_C}");

here引用此代码

【问题讨论】:

    标签: javascript regex


    【解决方案1】:

    {} 是正则表达式中的特殊字符,您必须将它们转义为模式:

    试试:

    commentString.replace(/\{firstname\}/g, '{firstname_C}')
    

    【讨论】:

    • 我试过你的解决方案:commentString = commentString.replace(/\{firstname\}{202}/g, "{firstname_C}");
    • 非常适合我:'{firstname} will continue to learn high frequency words, try to remember words and us them in their writing. {firstname} always uses correct spacing in their writing and attempts to use punctuation.'.replace(/\{firstname\}/g, '{firstname_C}')
    • 问题是我只需要在特定索引处替换..您的代码中没有包含索引 202
    • 如果您已经知道索引,为什么要使用正则表达式? stackoverflow.com/questions/2236235/…
    • 来吧,我只是想帮忙。您以任何方式确定了特定索引,因此该索引在运行时是已知的,并且您知道要替换的文本的确切长度。尝试在不使用正则表达式的情况下自己找出解决方案。
    猜你喜欢
    • 1970-01-01
    • 2021-02-03
    • 2017-11-17
    • 2017-05-13
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 2021-09-13
    • 2019-04-14
    相关资源
    最近更新 更多