doukanmang3687 2013-11-24 13:43
浏览 363
已采纳

在javascript中在字符串的第3个最后位置添加一个字符

So I have a var with value in digits and i want to add '=' sign at the third last position such that

var num = 98564;

would become

985=64

by googling I came accross this function

String.prototype.insert = function (index, string) {
  if (index > 0)
    return this.substring(0, index) + string + this.substring(index, this.length);
  else
    return string + this;
}

I think it will do my job, but I also want to keep a condition that if var num = 98; (2 digits) then the output should be 0=98

can you help me modifying that function? also guide me to do the same in PHP (any inbuilt function that you know?) Thanks!

  • 写回答

1条回答 默认 最新

  • dougutuo9879 2013-11-24 14:04
    关注

    PHP

    function new_num($int) {
        $new_num = (isset($int) ? (strlen($int) > 2 ? substr_replace($int, '=', strlen($int)-2, 0) : '0=' . $int) : null);
        return $new_num;
    }
    
    $num = 16000;
    $new_num = new_num($num);
    

    The function will check that the input is set (although it's a bit redundant in a function seeing as the variable is required, I put it there in case you didn't want it to be a function) and then check if the length of the input is greater than 2. If greater than 2, it will insert the "=", otherwise it will add "0=" to the front. The javascript is doing essentially the same thing but just to note it has to be converted to a string to manipulate it with substring, length, etc.

    Javascript:

    var num = 16000;
    num = num.toString();
    if (num.length > 2) {
        var new_num = num.substring(0, num.length-2) + '=' + num.slice(-2);
    } else {
        var new_num = '0=' + num;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么