DPatrick
DPatrick

Reputation: 59

TypeScript: How to replace a particular number in a string, and then update its value?

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:

  1. Input an index number X
  2. Locate the corresponding number in the string
  3. Add or subtract a particular number A to/from that number to update the string
  4. Update the string

A complete example below:

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

Answers (2)

woocash19
woocash19

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

cSharp
cSharp

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

Related Questions