dselp3944 2013-06-20 06:01
浏览 82
已采纳

Jquery在固定位置替换数字

I am writing a function which is used to replace the class of div in certain conditions, for example,

  1. condition A - the div class is e_new_hazard_frame_2_1_4_7, I want to replace the 2 to 1, outcome should be like this - e_new_hazard_frame_1_1_4_7
  2. condition B - the div class is the same with above, I want to replace the 1 to 4, outcome should be like this - e_new_hazard_frame_2_4_4_7
  3. condition C - the div class is the same with above, I want to replace the 4 to 6, outcome should be like this - e_new_hazard_frame_2_1_6_7
  4. condition D - the div class is the same with above, I want to replace the 7 to 3, outcome should be like this - e_new_hazard_frame_2_1_4_3

these 4 numbers might be the same, like 1_1_1_1, my demo coding is like var str = 'e_new_hazard_frame_2_1'; str = str.replace(/_[_0-9]*)$/,'1');

it seems not correct can anyone teach me how to do it? thank you so much!

  • 写回答

5条回答 默认 最新

  • dongliao1949 2013-06-20 06:13
    关注

    Maybe use a function to handle the numbers however you want?

    replace Javascript | MDN

    function replacer(match, p1, p2, p3, p4, offset, string){
      // p1-4 are your numbers 
      // (they are strings right now, sto make +p1 to convert them to int)
      p1= +p1 + 1;
      p2= +p2 + 1;
      p3= +p3 + 1;
      p4= +p4 + 1;
    
      // fixed a small bug here
      return ['', p1, p2, p3, p4].join('_');
    };
    
    var str = "asdasdasd_1_2_3_4";
    str = str.replace(/_(\d)_(\d)_(\d)_(\d)/, replacer);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 C#调用python代码(python带有库)
  • ¥15 矩阵加法的规则是两个矩阵中对应位置的数的绝对值进行加和
  • ¥15 活动选择题。最多可以参加几个项目?
  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型
  • ¥15 vs2019中数据导出问题
  • ¥20 云服务Linux系统TCP-MSS值修改?
  • ¥20 关于#单片机#的问题:项目:使用模拟iic与ov2640通讯环境:F407问题:读取的ID号总是0xff,自己调了调发现在读从机数据时,SDA线上并未有信号变化(语言-c语言)
  • ¥20 怎么在stm32门禁成品上增加查询记录功能
  • ¥15 Source insight编写代码后使用CCS5.2版本import之后,代码跳到注释行里面
  • ¥50 NT4.0系统 STOP:0X0000007B