Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS string.split() without removing the delimiters [duplicate]

How can I split a string without removing the delimiters?

Let's say I have a string: var string = "abcdeabcde";

When I do var newstring = string.split("d"), I get something like this:

["abc","eabc","e"]

But I want to get this:

["abc","d","eabc","d","e"]

When I tried to do my "split2" function, I got all entangled in splice() and indexes and "this" vs "that" and ... aargh! Help! :D

like image 364
Martin Janiczek Avatar asked Dec 22 '10 22:12

Martin Janiczek


People also ask

How do you split a string without delimiters?

Q #4) How to split a string in Java without delimiter or How to split each character in Java? Answer: You just have to pass (“”) in the regEx section of the Java Split() method. This will split the entire String into individual characters.

Does split () alter the original string?

Note: The split() method does not change the original string. Remember – JavaScript strings are immutable. The split method divides a string into a set of substrings, maintaining the substrings in the same order in which they appear in the original string. The method returns the substrings in the form of an array.

What can I use instead of split in JavaScript?

Slice( ) and splice( ) methods are for arrays. The split( ) method is used for strings. It divides a string into substrings and returns them as an array.


1 Answers

Try:

"abcdeabcde".split(/(d)/); 
like image 181
Kai Avatar answered Sep 18 '22 18:09

Kai