Reputation: 59
I am very new to TypeScript, and I can't wrap my head around how to replace a particular number in a string, and then update its value.
I have a column that is full of 10-digits string (e.g. 3345678901
)
I would like to be able to:
A complete example below:
6
8
3345878901
I know that since string is immutable, I need to create a new string and replace necessary characters. Also in order to be able to add/subtract certain values from a value, I need to convert it to an integer first .. a bit lost here.
Any help would be greatly appreciated!
Upvotes: 0
Views: 1463
Reputation: 76
const inputStr = "3345678901";
const inputIndex = 4;
const increaseAmount = 2;
let x = Number(inputStr[inputIndex]) + increaseAmount
const result = inputStr.substring(0,inputIndex) + x + inputStr.substring(inputIndex + 1)
console.log(result);
Upvotes: 0
Reputation: 3159
Try something like this. Below code takes care of carry.
const givenStr = "3345678901";
let givenStrArray = givenStr.split('').map(Number);
const inputIndex = 4;
const increaseAmount = 2;
let givenStrNumber = 0;
for (let i = 0; i < givenStrArray.length; i++) {
givenStrNumber += givenStrArray[i] * Math.pow(10, givenStrArray.length - i - 1)
}
givenStrNumber += increaseAmount * Math.pow(10, givenStrArray.length - inputIndex - 1)
console.log(givenStrNumber);
Upvotes: 1