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

在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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?