1

I need to split a big string into 5 words and return a sentence from these 5 words. Example:


// The string that needs to be split
'Hello, this is a very big string that goes on for loooooooooong'

// The output i need
'Hello, this is a very

I know I can use split(' ', 5) to separate the first 5 words, but i don't know how to put them back together into a sentence. Thanks in advance for your help and i you need me to clearer just ask.

Yurdesou
  • 179
  • 1
  • 2
  • 6

3 Answers3

2

You just need to rejoin the splitted array:

split(' ', 5).join(' ');
eogabor
  • 242
  • 4
  • 14
  • I found that out literally 20 seconds after i asked the question. Thank you very much anyway, i'll verify you answer in 12 min. – Yurdesou Dec 02 '21 at 12:26
2

Using Array.prototype.join() which creates and returns a new string by concatenating all of the elements in an array.

const s = 'Hello, this is a very big string that goes on for loooooooooong';

const str = s.split(' ', 5).join(' ');

console.log(str);

More about Array.prototype.join() - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join

Ran Turner
  • 14,906
  • 5
  • 47
  • 53
1

You can easily achieve the result using split, slice and join and using regex /\s+/

enter image description here

const str = "Hello, this is a very big string that goes on for loooooooooong";

const result = str.split(/\s+/).slice(0, 5).join(" ");
console.log(result);
DecPK
  • 24,537
  • 6
  • 26
  • 42