2

Im generating a simple random number which is generating 6 digit number. i want to break it in two parts 3 by 3. Example if number is 456123 it will break line number1=456 and number2=123

Im generating number like this

Number = Math.random().toString().substr(-6);
Bunyamin Coskuner
  • 8,719
  • 1
  • 28
  • 48
Umaiz Khan
  • 1,319
  • 3
  • 20
  • 66
  • Possible duplicate of [Javascript elegant way to split string into segments n characters long](https://stackoverflow.com/questions/6259515/javascript-elegant-way-to-split-string-into-segments-n-characters-long) – manish kumar May 20 '19 at 05:38

2 Answers2

2

you can use Regex match() like this

Math.random().toString().substr(-6).match(/.{1,3}/g)
Sunil Kashyap
  • 2,946
  • 2
  • 15
  • 31
2

If you want to do this numerically rather than converting to a string, you can do the math to get both parts using mod 1000 for the right part and then subtract and divide the left:

let n = 456123

let r = n % 1000
let l = (n - r) / 1000

console.log(l, r)

This assumes you want 0 if the right part is 0 rather than the string 000 (which you can get by padding it if you need that).

Mark
  • 90,562
  • 7
  • 108
  • 148
  • This is _probably_ the fastest but definitely the sanest. – Evert May 20 '19 at 06:02
  • Yeah, @Evert, it seems much faster to stick with numbers -- thought both are probably fast enough and the string might be more convenient depending on the use: https://jsperf.com/to-string-v-mod/1 – Mark May 20 '19 at 06:12