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 !
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.
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.
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.
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.
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 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With