1

I have an int variable that basically looks something like this:

101137111

What I want to do, is replace an INT at a particular point. So for example, if I wanted to change the 7 with a 9. How would I achieve that? Bearing in mind that I don't want to search for a 7, because there might be 7's before.

So, another example:

var number = 101137111;
var newNumber;

newNumber = number.replaceAtPosition('4') andReplaceWith (9);

so now that should change the 3 to a 9

animuson
  • 53,861
  • 28
  • 137
  • 147
Oliver Jones
  • 1,420
  • 7
  • 27
  • 43

4 Answers4

2

You can easily adapt Cem Kalyoncu's answer to fit your needs; By converting your number to a String, then calling the replaceAt() function.

// Cem's code
String.prototype.replaceAt = function(index, char) {
    return this.substr(0, index) + char + this.substr(index+char.length);
};
// End of Cem's code

var nb = 123456789;
var str = nb.toString();
str = str.replaceAt(5, '0'); // note the quotes around the number
Community
  • 1
  • 1
Pierre
  • 18,643
  • 4
  • 41
  • 62
1
function replaceAtPosition(number,index,replacement){
    number += '';//to string
    number = number.substring(0,index) + replacement + number.substring(index+1);
    return +number; // to int
}

use it like :

var number = 101137111;
var newNumber = replaceAtPosition(number,4,9);

See this live demo :

http://jsfiddle.net/gion_13/m86yt/

gion_13
  • 41,171
  • 10
  • 96
  • 108
0

cast it to a string an change the characters you want one by one.

use toString() to get the int to a string

and then here's an intro to search and replace chars> http://forums.techguy.org/software-development/680103-javascript-search-replace-single-characters.html

Once done cast back to an int !

BuZz
  • 16,318
  • 31
  • 86
  • 141
0
var number = 101137111;
var newNumber = number.toString();
newNumber[4] = 9;
newNumber = +newNumber;

So basically, convert to string, replace then convert back.

However the elegant solution would use bit manipulation of the number because that's faster. (Don't ask me how to do bit magic!)

Raynos
  • 166,823
  • 56
  • 351
  • 396