【问题标题】:using javascript replace() to match the last occurance of a string使用 javascript replace() 匹配最后一次出现的字符串
【发布时间】:2014-08-23 16:09:51
【问题描述】:

我正在为产品变体构建一个“添加新行”功能,并且我正在努力使用匹配表单属性键所需的正则表达式。所以,我基本上是在克隆行,然后增加键,就像这样(coffeescript):

  newrow = oldrow.find('select, input, textarea').each ->
    this.name = this.name.replace(/\[(\d+)\]/, (str, p1) ->
      "[" + (parseInt(p1, 10) + 1) + "]"
    )
    this.id = this.id.replace(/\_(\d+)\_/, (str, p1) ->
      "_" + (parseInt(p1, 10) + 1) + "_"
    )
  .end()

这会正确递增名称为 product[variations][1][name] 的字段,将其转换为 product[variations][2][name]

但是每个变体都可以有多个选项(例如,颜色可以是红色、蓝色、绿色),所以我需要能够将这个product[variations][1][options][2][name] 转换为product[variations][1][options][3][name],而不用单独保留变体键。我需要什么正则表达式来匹配最后一次出现的键(选项键)?

【问题讨论】:

    标签: javascript regex coffeescript


    【解决方案1】:

    您可以为此使用负前瞻:

    /\[(\d+)\](?!.*\[\d+\])/
    

    (?!_____) 部分是负前瞻。

    这就是说:仅当字符串后面的方括号中没有数字时,才匹配和捕获方括号之间的数字。 Live Explanation

    var m = "product[variations][1][options][3][name]".match(/\[(\d+)\](?!.*\[\d+\])/);
    console.log(m[1]); // "3"
    

    【讨论】:

    • 我在这个问题上卡了 3 个小时,你在 2 分钟内解决了它。谢谢!
    【解决方案2】:

    如果可能的话,有时我也喜欢使用 split :

    var a = 'product[variations][1][options][2][name]'.split('][');
    // you can then replace before last value :
    a[a.length-2] = indexYouWish;
    var newName = a.join('][');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-17
      • 1970-01-01
      • 1970-01-01
      • 2012-04-14
      • 2011-02-03
      • 1970-01-01
      相关资源
      最近更新 更多