How to split string by whitespace javascript
I would like to split a String but I would like to keep white space like: Show
How I can proceed to do that? Thanks ! asked Oct 17, 2014 at 13:02
Using regex:
answered Oct 17, 2014 at 13:06
chridamchridam 97k21 gold badges223 silver badges227 bronze badges 5 You could split the string on the whitespace and then re-add it, since you know its in between every one of the entries.
Update: Removed trailing space. answered Oct 17, 2014 at 13:04
somethingheresomethinghere 15.6k2 gold badges27 silver badges42 bronze badges 3 For split string by space like in Python lang, can be used:
output:
or similar:
(output some) answered Sep 21, 2016 at 22:36
iqmakeriqmaker 2,05324 silver badges22 bronze badges 2 You can just split on the word boundary using "\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
The initial EDIT: Added grouping answered Oct 17, 2014 at 13:07
RhumborlRhumborl 16k4 gold badges36 silver badges45 bronze badges 2 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.
So:
Output:
This collapses consecutive spaces in the original input, but otherwise I can't think of any pitfalls. answered Oct 17, 2014 at 13:13
In case you're sure you have only one space between two words, you can use this one
so you replace one space by two, the split by space answered Oct 26, 2020 at 11:32
answered Jul 11, 2016 at 20:40
EsgerEsger 1,12911 silver badges17 bronze badges 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 I split a space in JavaScript?To split a string keeping the whitespace, call the split() method passing it the following regular expression - /(\s+)/ . The regular expression uses a capturing group to preserve the whitespace when splitting the string.
Can we split 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.
Which JavaScript method is used to break a string on a character or whitespace?str. split() method is used to split the given string into array of strings by separating it into substrings using a specified separator provided in the argument. separator: It is used to specified the character, or the regular expression, to use for splitting the string.
|