在javascript中在字符串的第3个最后位置添加一个字符(Add a character at the 3rd last position of the string in javascript)

编程入门 行业动态 更新时间:2024-10-28 04:23:46
在javascript中在字符串的第3个最后位置添加一个字符(Add a character at the 3rd last position of the string in javascript)

所以我有一个带有数字值的var,我想在第三个最后位置加上'='符号

var num = 98564;

会成为

985=64

通过谷歌搜索我来到这个功能

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

我认为它会完成我的工作,但我也希望保持条件,如果var num = 98; (2位数)然后输出应为0=98

你能帮我修改一下这个功能吗? 还指导我在PHP中做同样的事情(你知道的任何内置函数吗?)谢谢!

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!

最满意答案

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);

该函数将检查输入是否已设置(虽然在函数中看起来有点多余,因为变量是必需的,我把它放在那里,以防你不想让它成为函数)然后检查是否有长度输入大于2.如果大于2,则会插入“=”,否则会在前面添加“0 =”。 javascript基本上是做同样的事情,但只是要注意它必须转换为字符串,以使用子字符串,长度等操纵它。

使用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; }

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; }

更多推荐

本文发布于:2023-07-29 23:59:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1320792.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   字符   位置   javascript   string

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!