0

I'm trying to find a way to split long strings to multiple lines so what I'm doing is insert text into an image and if it gets too long it overflows, newlines work but it wouldn't be best idea to let user add the newlines and split it in code, so if i give it a limit it checks if its over limit split to two lines or i mean a newline \n between it, however that's easy but my problem is when it comes that the second part is also over the limit then it should split it in to 3 newlines, how would you go implement that?

Examples

split("sometext", 5); // somet\next
split("Hello", 2); // he\nll\no

4 Answers 4

3

Very straightforward answer to your question:

function customSplit(str, maxLength){
    if(str.length <= maxLength)
        return str;
    var reg = new RegExp(".{1," + maxLength + "}","g");
    var parts = str.match(reg);
    return parts.join('\n');
}
Sign up to request clarification or add additional context in comments.

Comments

2

You need a function like the following:

function split(str, maxWidth) {
  const newLineStr = "\n";
  done = false;
  res = '';
  do {
    found = false;
    // Inserts new line at first whitespace of the line
    for (i = maxWidth - 1; i >= 0; i--) {
      if (testWhite(str.charAt(i))) {
        res = res + [str.slice(0, i), newLineStr].join('');
        str = str.slice(i + 1);
        found = true;
        break;
      }
    }
    // Inserts new line at maxWidth position, the word is too long to wrap
    if (!found) {
      res += [str.slice(0, maxWidth), newLineStr].join('');
      str = str.slice(maxWidth);
    }

    if (str.length < maxWidth)
      done = true;
  } while (!done);

  return res + str;
}

function testWhite(x) {
  const white = new RegExp(/^\s$/);
  return white.test(x.charAt(0));
};
console.log(split("sometext", 5));
console.log(split("Hello", 2));

Comments

0

https://j11y.io/snippets/wordwrap-for-javascript/

Wraps using specified limit on characters. :)

Comments

0

What kind of interface are you building? If it's a web interface, you should style the string on the front end, instead of modifying it on the data layer.

If it's a text based interface and you really need to do this, then you can get the first n characters while there is a non-empty string, then join with '\n'. Assuming you have underscore:

function split(str, n) {
  let numberOfSegments = Math.ceil(_.size(str) / n);
  let segments = _.map(_.range(numberOfSegments), 
                       segmentIndex => str.substr(segmentIndex * n, n));
  return segments.join('\n');
}

1 Comment

No its not a web interface, just some stuff in node.js

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.