Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert dashes into a number

Tags:

javascript

Any ideas on the following? I want to input a number into a function and insert dashes "-" between the odd digits. So 4567897 would become "456789-7". What I have so far is to convert the number into a string and then an array, then look for two odd numbers in a row and use the .splice() method to add the dashes where appropriate. It does not work and I figure I may not be on the right track anyway, and that there has to be a simpler solution.

function DashInsert(num) { 
  var numArr = num.toString().split('');

    for (var i = 0; i < numArr.length; i++){
    if (numArr[i]%2 != 0){
      if (numArr[i+1]%2 != 0) {
          numArr.splice(i, 0, "-");
          }
        }
  }  
  return numArr;      
}
like image 376
user2623706 Avatar asked May 09 '26 09:05

user2623706


2 Answers

The problem is you're changing the thing you're iterating over. If instead you maintain a separate output and input...

function insertDashes(num) {
  var inStr = String(num);
  var outStr = inStr[0], ii;

  for (ii = 1; ii < inStr.length; ii++) {
    if (inStr[ii-1] % 2 !== 0 && inStr[ii] % 2 !== 0) {
      outStr += '-';
    }

    outStr += inStr[ii];
  }

  return outStr;
}
like image 80
OrangeDog Avatar answered May 11 '26 21:05

OrangeDog


You can try using regular expressions

'4567897'.replace(/([13579])(?=[13579])/g, '$1-')

Regex Explained

So, we find an odd number (([13579]) is a capturing group meaning we can use it as a reference in the replacement $1) ensure that it is followed by another odd number in the non-capturing positive lookahead ((?=[13579])) and replace the matched odd number adding the - prefix

like image 22
shyam Avatar answered May 11 '26 21:05

shyam