Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 !

like image 610
Jose Avatar asked Oct 17 '14 13:10

Jose


People also ask

How do you split a string in white space?

You can split a String by whitespaces or tabs in Java by using the split() method of java. lang. String class. This method accepts a regular expression and you can pass a regex matching with whitespace to split the String where words are separated by spaces.

How do you write white space in JavaScript?

A common character entity used in HTML is the non-breaking space ( ). Remember that browsers will always truncate spaces in HTML pages. If you write 10 spaces in your text, the browser will remove 9 of them. To add real spaces to your text, you can use the   character entity.

Which JavaScript method is used to break a string on a character or whitespace?

JavaScript String split() Method. JavaScript str. split() method is used to split the given string into an array of strings by separating it into substrings using a specified separator provided in the argument. separator: It is used to specify the character, or the regular expression, to use for splitting the string.

Can you split a string in JavaScript?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.


2 Answers

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.

like image 65
chridam Avatar answered Sep 18 '22 10:09

chridam


You could split the string on the whitespace and then re-add it, since you know its in between every one of the entries.

var string = "text to split";     string = string.split(" "); var stringArray = new Array(); for(var i =0; i < string.length; i++){     stringArray.push(string[i]);     if(i != string.length-1){         stringArray.push(" ");     } } 

Update: Removed trailing space.

like image 25
somethinghere Avatar answered Sep 19 '22 10:09

somethinghere