Home > front end >  How can I insert dashes between each 2 odds numbers and asterisks between even numbers in Javascript
How can I insert dashes between each 2 odds numbers and asterisks between even numbers in Javascript

Time:09-26

How can I write a function that insert dashes ('-') between each two odd numbers and insert asterisks ('*') between each two even numbers?

For example: if num is 4005467930 the output should be: 40054*67-9-30. I Did not count zero as an odd or even number. below is my code: I tried to use continue to loop over zero , but it didn't work. There is also dash('-') in the begining of the printed result. How can I overcome this

function StringChallenge(num) {

    let newString = num.toString();
    let result = '';
   
    for (let i = 0; i <newString.length; i  ) {
      let previous_number = newString[i-1];
      let current_number = newString[i];

      if(current_number === 0 || previous_number === 0 ){
        result  = current_number
        continue
      } else
        if(previous_number % 2 == 0 && current_number % 2 == 0) {
            result  = "*"   current_number
            console.log(result)
        } else if(previous_number % 2 !== 0 && current_number % 2 !== 0) {
            result  = "-"   current_number
            console.log(result)
        } else {
            result  = current_number
            console.log(result)
        }
        
        
    }
    return result
}
console.log(StringChallenge(4005467930))   // -4*0*054*67-9-30; I want it to be: 40054*67-9-30 //

CodePudding user response:

We can try a simple regex approach here:

function StringChallenge(num) {
    return num.replace(/(?<=[2468])(?=[2468])/g, "*")
              .replace(/(?<=[13579])(?=[13579])/g, "-");
}

var number = "4005467930";
console.log(number   " => "   StringChallenge(number));

Here is an explanation of the regex patterns:

  • (?<=[2468])(?=[2468]) this matches any point in the string surrounded on both sides by an even digit (excluding zero)
  • (?<=[13579])(?=[13579]) this matches any point in the string surrounded on both sides by an odd digit
  • Related