How can I chunk a string in JavaScript respecting words?
Ad
I have a large block of text and I want to split that into an array with each element being one line of up to 50 characters. If the string contains a \r
or \n
, I want that to be an element itself (not part of another string). I'm a bit perplexed on how to do this.
I've tried
lines = newVal.match(/^(\r\n|.){1,50}\b/g)
I've also tried underscore / lodash _.chunk
but that ignores words obviously.
But this gives me only the first match. Please help.
Ad
Answer
Ad
Try this:
result = lines.split(/(?=(\r\n))/g);
result.forEach(function(item,index,arr) {
if(item.length > 50) {
var more = item.match(/.{1,50}\b/g);
arr[index] = more[0];
for(var i=1; i<more.length; ++i) {
arr.splice(index+i, 0, more[i]);
}
}
});
This will first split the text into an array by your newlines, then go and further break up the long lines in the array, maintaining the words.
Ad
source: stackoverflow.com
Related Questions
Ad
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
Ad