Skip to content Skip to sidebar Skip to footer

Splitting A String Based On Max Character Length, But Keep Words Into Account

So In my program I can receive strings of all kinds of lengths and send them on their way to get translated. If those strings are of a certain character length I receive an error,

Solution 1:

What you are looking for is lastIndexOf

In this example, maxOkayStringLength is the max length the string can be before causing an error.

myString.lastIndexOf(/\s/,maxOkayStringLength);

-- edit --

lastIndexOf doesn't take a regex argument, but there's another post on SO that has code to do this:

Is there a version of JavaScript's String.indexOf() that allows for regular expressions?

Solution 2:

Here's an example using reduce.

const str = "this is an input example of one sentence that contains a bit of words and must be split";

// Split up the string and use `reduce`// to iterate over itconst temp = str.split(' ').reduce((acc, c) => {

  // Get the number of nested arraysconst currIndex = acc.length - 1;

  // Join up the last array and get its lengthconst currLen = acc[currIndex].join(' ').length;

  // If the length of that content and the new word// in the iteration exceeds 20 chars push the new// word to a new arrayif (currLen + c.length > 20) {
    acc.push([c]);

  // otherwise add it to the existing array
  } else {
    acc[currIndex].push(c);
  }

  return acc;

}, [[]]);

// Join up all the nested arraysconst out = temp.map(arr => arr.join(' '));

console.log(out);

Solution 3:

I would suggest:

1) split string by space symbol, so we get array of words

2) starting to create string again selecting words one by one...

3) if next word makes the string exceed the maximum length we start a new string with this word

Something like this:

constsplitString = (str, lineLength) => {
  const arr = ['']

  str.split(' ').forEach(word => {
    if (arr[arr.length - 1].length + word.length > lineLength) arr.push('')
    arr[arr.length - 1] += (word + ' ')
  })

  return arr.map(v => v.trim())
}
const str = "this is an input example of one sentence that contains a bit of words and must be split"console.log(splitString(str, 20))

Solution 4:

You can use match and lookahead and word boundaries, |.+ to take care string at the end which are less then max length at the end

let str = "this is an input example of one sentence that contains a bit of words and must be split"console.log(str.match(/\b[\w\s]{20,}?(?=\s)|.+$/g))

Post a Comment for "Splitting A String Based On Max Character Length, But Keep Words Into Account"