1

My objective is to split string (less than 80 characters) evenly to create a square or rectangle of strings.

var squareStr = function(str) {

}

console.log(squareStr('whatwonderfulday'));
console.log(squareStr('if life was easy god then god would not have given us brain to think'));

should output:

what
wond
erfu
lday

iflifewa
seasythe
ngodwoul
dnothave
givenusb
raintoth
ink

is this possible? I've been told I can use Math.sqrt but I'm not too sure how.

Thanks.

Binny.H
  • 83
  • 6
  • If the length of the string isn't a number evenly divisible by four then this couldn't work. – yaakov May 04 '18 at 20:23
  • 2
    Sure it's possible, what have you tried? – skyline3000 May 04 '18 at 20:25
  • take a look at [Split array into chunks](https://stackoverflow.com/questions/8495687/split-array-into-chunks) – Taki May 04 '18 at 20:30
  • I have an answer ready to post here, but i'm waiting to see what you have tried or researched so far. – Calvin Nunes May 04 '18 at 20:33
  • I've tried str.match(/.{1,3}/g) - but that only does it by fixed amount. I want it to do it calculate it on its own (if that's possible). – Binny.H May 04 '18 at 20:38
  • Use `floor(Math.sqrt(string.length))` as the length of each line. – Barmar May 04 '18 at 20:46
  • Your second example is not a square. It has 8 columns but only 7 rows. – Barmar May 04 '18 at 20:52
  • @YaakovAinspan What does division by 4 have to do with it? And his second example shows that the last line can be incomplete. – Barmar May 04 '18 at 20:56
  • The title says you want a square, but the question says "square or rectangle". Which is it? And if it's a rectangle, are there constraints on the height or width? – Barmar May 04 '18 at 20:57

4 Answers4

3

You can use a for loop to slice the string into the pieces and add a new line (\n) at the end of each chunk.

If you want to automatically use the square root of the string length you can do it like this:

function squareCode(string){
  let squareString = "";
  string = string.replace(/\s/g, '');
  const splitNum = Math.floor(Math.sqrt(string.length));
  for(i=0; i<= string.length; i+=splitNum){
    squareString = `${squareString}${string.slice(i, i+splitNum)}\n`;
  }
  return squareString;
}

console.log(squareCode('whatwonderfulday'));
console.log(squareCode('if life was easy god then god would not have given us brain to think'));
console.log(squareCode('asdfasdf asdfasdfasd fasdfwe wer df gf dgdfgertqewdfsf fgdgewfwdsgewerfsd fdgdfgqefasdf'));

In the following function you'll pass in the string you want to slice as well as the number you want to slice at:

function squareCode(string, splitNum){
  let squareString = "";
  string = string.replace(/\s/g, '');
  for(i=0; i<= string.length; i+=splitNum){
    squareString = `${squareString}${string.slice(i, i+splitNum)}\n`;
  }
  return squareString;
}

console.log(squareCode('whatwonderfulday', 4));
console.log(squareCode('if life was easy god then god would not have given us brain to think', 8));
Cory Kleiser
  • 1,969
  • 2
  • 13
  • 26
2

You could use this function. It replace all the empty spaces, then convert the string into an array and chunk it. Finally if merge every chunk and apply \n to each one.

var squareStr = function(str, chunk) {
  str = str.replace(/ /g, '')
  str = str.split('');
  temp = []
  for (i=0; i<str.length; i+=chunk)
    temp.push(str.slice(i,i+chunk));
  return temp.map(function(a){return a.join('')+"\n"}).join('')
}

console.log(squareStr('whatwonderfulday', 4));
console.log(squareStr('if life was easy god then god would not have given us brain to think', 8));
1

So many ways of doing that...

All other answers here are correct too, here's my approach, a more "readable" answer, using very basic recurses...

You have should at least tried...

I also have included a check to see if the string lenght is under 80.

var squareStr = function(str, charsPerLine) {
  if (str.length > 80){
    return;
  }
  str = str.replace(/ /g,'')
  var stringSplited = str.split('');  
  var newString = '';
  
  stringSplited.forEach(function(letter,index){
    if (index % charsPerLine == 0 && newString.length > 0){
      newString += '\n'; //IF YOU WANT TO USE IT IN THE HTML, USE '<br>' HERE
    }
    newString += letter;
  }); 
  console.log(newString);
  return newString;
}


squareStr('whatwonderfulday', 4);
squareStr('if life was easy god then god would not have given us brain to think', 8);
Calvin Nunes
  • 6,376
  • 4
  • 20
  • 48
0

Unless you're dealing with really long strings, I don't see a reason not to use replace to insert a newline every n characters:

function squareText(input) {
  const inputNoSpaces = input.replace(/\s/g, '');
  const partLen = Math.ceil(Math.sqrt(inputNoSpaces.length));
  const replaceExpr = new RegExp(`.{1,${partLen}}`, 'g');
  return inputNoSpaces.replace(replaceExpr, '$&\n');
}

const input = 'if life was easy then god would not have given us brain to think';
console.log(squareText(input));

This just calculates the line length and then creates a new RegExp that matches that many characters and uses it to replace each match with itself plus a newline.

Jordan Running
  • 102,619
  • 17
  • 182
  • 182