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:
- Input an index number X
- Locate the corresponding number in the string
- Add or subtract a particular number A to/from that number to update the string
- Update the string
A complete example below:
- Input index number "4"
- The corresponding number is
6
- Increase that number by 2 to
8
- Update the string to
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!
CodePudding user response:
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);
CodePudding user response:
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);