Alisha Sharma
Alisha Sharma

Reputation: 149

split word from string including space using js

I am trying to split string including string but space are also spitted.

my code:-

var a ='                     that i love          
           game1           ';
console.log(a.split(' '))

my current output is like:-

(57) ["↵", "", "", "", "", "", "", "", "", "that", "i", "love↵", "", "", "", "", "", "", "", "", "game1↵↵↵", "", "", "", ""]

Output that I am trying to get somthing like this:-

 (4)["              that",'i','               love','   ↵game'];

How can I split string in such a way including space and line break??

Please don't suggest me idea using jquery

Upvotes: 0

Views: 68

Answers (2)

Thushan
Thushan

Reputation: 1330

You can use regex in split.

var a =`                     that i love         
           game1           `;
console.log(a.split(/(\s+\S+\s+)/));

Upvotes: 1

Ori Drori
Ori Drori

Reputation: 191916

You can use String#match with a regular expression (regex101) to get something similar to what you want:

var a =`                     that i love          
           game1           `;

console.log(a.match(/\s*\S*/g));
 
// or

console.log(a.match(/\s*\S*\s*/g));

Upvotes: 7

Related Questions