-1

I have a string like 'oeew9w79WMIGL'. I want to get an output like below,

oee
w9w
79W
MIG
L

How to do it with plain JavaScript?

Anijit Sau
  • 555
  • 2
  • 8
  • 25

4 Answers4

2

You could replace a part of the string.

var string = 'oeew9w79WMIGL';

console.log(string.replace(/.../g, '$&\n'));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • Thanks for your one liner approach. Both of you and @Viking code are right.. But I can't tick two solution. – Anijit Sau Apr 27 '17 at 09:28
1

if you use regex

let str = 'oeew9w79WMIGL';

document.write(str.match(/.{1,3}/g));
   
VikingCode
  • 1,022
  • 1
  • 7
  • 20
0

$(document).ready(function(){
 var foo = "oeew9w79WMIGL";
$('#test').html(foo.match(/.{1,3}/g).join("<br />") );
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="test">
</span>
 var str= "oeew9w79WMIGL";
console.log( str.match(/.{1,3}/g).join("<br />") );
Amit Kumar
  • 5,888
  • 11
  • 47
  • 85
0
 each_slice = function(enm, slice_size) {
   var results = [];
     slice_size = (slice_size < 1 ? 1 : slice_size ); 
       for (var i=0; i<=enm.length; i=i+3) {
         results.push(enm.slice(i, i+3));
      }
  return results;
}

var x = "oeew9w79WMIGL";
each_slice(x,3).join("\n")

//oee
//w9w
//79W
//MIG
//L

for reference: https://stackoverflow.com/a/41219012/4481312

Community
  • 1
  • 1
marmeladze
  • 6,468
  • 3
  • 24
  • 45