Home > OS >  How to remove a particular digit from an integer using javascript
How to remove a particular digit from an integer using javascript

Time:04-07

I have an integer containing various digits, I want to remove 4th digit from an integer. How can I achieve that ?

Example :

let number = 789012345

Here I want to remove 0

CodePudding user response:

Try this :

// Input
let number = 789012345;

// Convert number into a string
let numberStr = number.toString();

// Replace the 0 with empty string
const res = numberStr.replace(numberStr[3], '');

// Convert string into a number.
console.log(Number(res));

CodePudding user response:

let numberWithoutADigit = removeIthDigitFromNumber(789012345, 4);

function removeIthDigitFromNumber(n, i){
    //convert the number n to string as an array of char
    let o = (n   '').split('');
    //remove the item at the index i (0 based) from the array
    o.splice(i, 1);
    //rebuilds the string from the array of char and parse the string to return a number
    let number = parseInt(o.join(''));

    return number;
}

CodePudding user response:

You can follow this procedure:

  • Decide if you want to remove digits by index or by value, the following demo will remove by value, which means it will remove all values that match
  • Convert the number into a string
  • Split the string
  • Use Array#filter to remove target digit(s)
  • Use Array#join to create a string
  • Use to convert to string back into a numeric value

const n = 789012345;
const m =  n.toString().split("").filter(num =>  num !== 0).join("");
console.log( m );

CodePudding user response:

let x=789012345
var nums = [];
let i = 0, temp = 0;
while(x > 1){
nums[i  ] = (x % 10);
x = (x - (x % 10)) / 10;
}
var cnt = 0;
for(--i; i >= 0; i--){
if(cnt   == 3) continue;
temp = temp * 10   nums[i];
}

CodePudding user response:

let number = 789012345  
let i = 3  // index 3, 4th digit in number

let arr = number.toString().split("").filter((value, index) => index!==i);
// ['7', '8', '9', '1', '2', '3', '4', '5']

let new_number = parseInt(arr.join(""))
// 78912345

console.log(new_number)

CodePudding user response:

Rohìt Jíndal's answer is excellent. I just want to point out another way you could do this with string.replace and capturing groups.

function removeDigit(input, index) {
  let exp = new RegExp(`^(\\d{${index}})(\\d)(. )$`);
  return parseInt(input.toString().replace(exp, '$1$3'));
}

let output = removeDigit(789012345, 3);
console.log(output); // 78912345

In this example, I have created a new RegExp object from a template literal in order to inject the index.

The first capturing group contains all digits up to the desired index. The second contains the digit we want to remove and the third contains the remainder of the string.

We then return an integer parsed from the string combination of only the first and third capturing groups.

  • Related