Moose9000
Moose9000

Reputation: 11

Bringing numbers to the front

(Javascript)

functionName(“2 plus 3 is = 5!”);

would produce following message in console:

235 plus is = 

I am unable to bring the numbers to the front, I am a little stumped

function frontNum(str) {
  let emptyArr   = [];
  let rev        = str.split("");
  let expression = /[\d]/g;
   
  for(let i = 0; i < rev.length; i++) {
    if (rev[i].match(expression)) {
      emptyArr += rev.pop(rev[i]);
    }
  }
  console.log(emptyArr + rev.join(''));
}

frontNum("2 plus 3 is = 5!");

Upvotes: 0

Views: 57

Answers (2)

Mister Jojo
Mister Jojo

Reputation: 22334

a way todo that

'use strict'

function frontNum(str)
  {
  let s = ''
    , n = ''  
  for (let x of str) 
    {
    if (/[0-9]/.test(x)) n += x 
    else                 s += x 
    }
  console.log( n + s.replace(/  +/g,' ') )
  }

frontNum('2 plus 3 is = 5!')

Upvotes: 0

vanowm
vanowm

Reputation: 10221

Since this is your home work I won't give you the correct version, but give you some pointers instead:

  1. your emptyArr is an array, but you are adding data to it as if it was a string.
  2. take a look at this topic, your pop causing problems
  3. you can use your expression to capture all the digits and remove them from the string without need converting the string into array and loop through it (it can be done with 2 lines of code)

Upvotes: 3

Related Questions