简体   繁体   中英

Add a character at the 3rd last position of the string in javascript

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM