I asked a similar question here TypeScript: How to replace a particular number in a string, and then update its value?
Really appreciate the answers there. It answered my questions.
I am run into a new issue. Thought it s more helpful to raise a new question while referring to the old question.
I have a column that is full of 10-digits string.
Sometimes that entire 10-digits only contain numerical values (e.g. 3345678901), but sometimes there is dash included (e.g. 3345678---)
I would like to be able to:
Example 1 (all numerical): 3345678901
683345878901Example 2 (numerical & non-numerical): 3345678---
683345878---Example 3 (numerical & non-numerical): 3345678---
-233458782--For example 1, I know I could do following (as a contributor from the OG post has pointed out):
const givenStr = "3345678901";
let givenStrArray = givenStr.split('').map(Number);
const inputIndex = 4;
const increaseAmount = 2;
givenStrNumber += increaseAmount
console.log(givenStrNumber);
But, how do I go about Example 2 and 3 though? Since there are string '-' involved? In this case map(Number) would lead to Null values that would break the code.
Any help would be greatly appreciated!
Check for NaN. This is a tiny snippet that would give you a hint:
// ...
// ...
const increment = 2;
let givenStrArray =
givenStr
.split('')
.map((digiit) => isNaN(digit) ? increment : Number(digit + increment);
// ...
// ...
This should do the trick
let str = '3345678---'
let NumericStrArray = str.split('').map(x => Number.isNaN(Number(x)) ? x: Number(x))
let ipIndex = 7
let incAmount = 2
let val = NumericStrArray[ipIndex]
NumericStrArray[ipIndex] = typeof val === 'string' ? incAmount : val + incAmount
let result = NumericStrArray.join('')
Here's a simple little snippet. Break the sting apart, map through each item, when we find the index we need to update we update it and return it, then join them all back together.
Multiple conditional ternary operator have been used here, you can find out more about how they work here: Conditional (ternary) operator
const givenStr = "334567----",
inputIndex = 6,
increaseAmount = 2
let givenNumber = givenStr
.split('')
.map((v,i) => i === inputIndex ? isNaN(v) ? increaseAmount : +v + increaseAmount : v)
.join('')
console.log(givenNumber);