[javascript] JavaScript split String with white space

I would like to split a String but I would like to keep white space like:

var str = "my car is red";

var stringArray [];

stringArray [0] = "my";
stringArray [1] = " ";
stringArray [2] = "car";
stringArray [3] = " ";
stringArray [4] = "is";
stringArray [5] = " ";
stringArray [6] = "red";

How I can proceed to do that?

Thanks !

This question is related to javascript arrays split

The answer is


In case you're sure you have only one space between two words, you can use this one

str.replace(/\s+/g, ' ').split(' ')

so you replace one space by two, the split by space


Using regex:

var str   = "my car is red";
var stringArray = str.split(/(\s+)/);

console.log(stringArray); // ["my", " ", "car", " ", "is", " ", "red"] 

\s matches any character that is a whitespace, adding the plus makes it greedy, matching a group starting with characters and ending with whitespace, and the next group starts when there is a character after the whitespace etc.


You can just split on the word boundary using \b. See MDN

"\b: Matches a zero-width word boundary, such as between a letter and a space."

You should also make sure it is followed by whitespace \s. so that strings like "My car isn't red" still work:

var stringArray = str.split(/\b(\s)/);

The initial \b is required to take multiple spaces into account, e.g. my car is red

EDIT: Added grouping


str.split(' ').join('§ §').split('§');

Although this is not supported by all browsers, if you use capturing parentheses inside your regular expression then the captured input is spliced into the result.

If separator is a regular expression that contains capturing parentheses, then each time separator is matched, the results (including any undefined results) of the capturing parentheses are spliced into the output array. [reference)

So:

var stringArray = str.split(/(\s+)/);
                             ^   ^
//

Output:

["my", " ", "car", " ", "is", " ", "red"]

This collapses consecutive spaces in the original input, but otherwise I can't think of any pitfalls.


For split string by space like in Python lang, can be used:

   var w = "hello    my brothers    ;";
   w.split(/(\s+)/).filter( function(e) { return e.trim().length > 0; } );

output:

   ["hello", "my", "brothers", ";"]

or similar:

   w.split(/(\s+)/).filter( e => e.trim().length > 0)

(output some)


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to split

Parameter "stratify" from method "train_test_split" (scikit Learn) Pandas split DataFrame by column value How to split large text file in windows? Attribute Error: 'list' object has no attribute 'split' Split function in oracle to comma separated values with automatic sequence How would I get everything before a : in a string Python Split String by delimiter position using oracle SQL JavaScript split String with white space Split a String into an array in Swift? Split pandas dataframe in two if it has more than 10 rows