Home > Software design >  Function to split text evenly within the given number in javascript
Function to split text evenly within the given number in javascript

Time:07-31

Is there a way to do this? lets say :

let text = "i have three apple"

let splittedText1 = split(text, 2)
let splittedText2 = split(text, 3)

console.log(splittedText1) // ["i have", "three apple"]
console.log(splittedText2) // ["i have", "three", "apple"]

the function does split the text into section by given number, say the text 5 word, and i want to split them by 3 word, it will split the 5 word into an array of 3 string

CodePudding user response:

I think I got it. I have used code from https://stackoverflow.com/a/8189268/3807365

let text = "i have three    apple"

console.log(split(text, 2))
console.log(split(text, 3))

function chunkify(a, n) {
  if (n < 2) return [a];

  var len = a.length,
    out = [],
    i = 0,
    size;

  if (len % n === 0) {
    size = Math.floor(len / n);
    while (i < len) {
      out.push(a.slice(i, i  = size));
    }
  } else {
    while (i < len) {
      size = Math.ceil((len - i) / n--);
      out.push(a.slice(i, i  = size));
    }
  }
  return out;
}

function split(text, n) {
  var arr = text.split(/\s /);
  var parts = chunkify(arr, n);
  return parts.map(item => item.join(" "));

}

CodePudding user response:

Assuming you always want the string "split" into two parts, you can use a combination of split and join to do this.

Example:

function splitStringAtSpace(str, n) {
  let s = str.split(" ");  // creates an array of substrings that occur at each space in the string
  let first = s.slice(0, n).join(" ");
  let second = s.slice(n).join(" ");
  return [first, second];
}

let str = "Hello there how are you";
console.log(splitStringAtSpace(str, 1));    // split after 1st space
console.log(splitStringAtSpace(str, 2));    // split after 2nd space
console.log(splitStringAtSpace(str, 3));  // split after 3rd space

  • Related