JS string.split() without removing the delimiters

JavascriptSplitDelimiter

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

Try:

"abcdeabcde".split(/(d)/);

Solution 2 - Javascript

I like Kai's answer, but it's incomplete. Instead use:

"abcdeabcde".split(/(?=d)/g) //-> ["abc", "deabc", "de"]

This is using a Lookahead Zero-Length Assertion in regex, which makes a match not part of the capture group. No other tricks or workarounds needed.

Solution 3 - Javascript

Try this:

  1. Replace all of the "d" instances into ",d"
  2. Split by ","

var string = "abcdeabcde";
var newstringreplaced = string.replace(/d/gi, ",d");
var newstring = newstringreplaced.split(",");
return newstring;

Hope this helps.

Solution 4 - Javascript

var parts= string.split('d');
for (var i= parts.length; i-->1;)
    parts.splice(i, 0, 'd');

(The reversed loop is necessary to avoid adding ds to parts of the list that have already had ds inserted.)

Solution 5 - Javascript

split - split is used to create separate lines not for searching.

[^d] - find a group of substrings not containing "d"

var str = "abcdeabcde";
 
str.match(/[^d]+|d/g)         // ["abc", "d", "eabc", "d", "e"]
or
str.match(/[^d]+/g)           // ["abc", "eabc", "e"]
or
str.match(/[^d]*/g)           // ["abc", "", "eabc", "", "e", ""]

Read "RegExp Object" if you do not want problems with the "javascript".

Solution 6 - Javascript

Try this:

var string = "abcdeabcde";
	var delim = "d";
	var newstring = string.split(delim);
	var newArr = [];
	var len=newstring.length;
	for(i=0; i<len;i++)
	{
		newArr.push(newstring[i]);
		if(i != len-1)newArr.push(delim);
	}

Solution 7 - Javascript

This is my version for regexp delimiters. It has same interface with String.prototype.split; it will treat global and non global regexp with no difference. Returned value is an array that odd member of it are matched delimiters.

function split(text, regex) {
    var token, index, result = [];
    while (text !== '') {
        regex.lastIndex = 0;
        token = regex.exec(text);
        if (token === null) {
            break;
        }
        index = token.index;
        if (token[0].length === 0) {
            index = 1;
        }
        result.push(text.substr(0, index));
        result.push(token[0]);
        index = index + token[0].length;
        text = text.slice(index);
    }
    result.push(text);
    return result;
}

// Tests
assertEquals(split("abcdeabcde", /d/), ["abc", "d", "eabc", "d", "e"]);
assertEquals(split("abcdeabcde", /d/g), ["abc", "d", "eabc", "d", "e"]);
assertEquals(split("1.2,3...4,5", /[,\.]/), ["1", ".", "2", ",", "3", ".", "", ".", "", ".", "4", ",", "5"]);
assertEquals(split("1.2,3...4,5", /[,\.]+/), ["1", ".", "2", ",", "3", "...", "4", ",", "5"]);
assertEquals(split("1.2,3...4,5", /[,\.]*/), ["1", "", "", ".", "2", "", "", ",", "3", "", "", "...", "4", "", "", ",", "5", "", ""]);
assertEquals(split("1.2,3...4,5", /[,\.]/g), ["1", ".", "2", ",", "3", ".", "", ".", "", ".", "4", ",", "5"]);
assertEquals(split("1.2,3...4,5", /[,\.]+/g), ["1", ".", "2", ",", "3", "...", "4", ",", "5"]);
assertEquals(split("1.2,3...4,5", /[,\.]*/g), ["1", "", "", ".", "2", "", "", ",", "3", "", "", "...", "4", "", "", ",", "5", "", ""]);
assertEquals(split("1.2,3...4,5.", /[,\.]/), ["1", ".", "2", ",", "3", ".", "", ".", "", ".", "4", ",", "5", ".", ""]);
assertEquals(split("1.2,3...4,5.", /[,\.]+/), ["1", ".", "2", ",", "3", "...", "4", ",", "5", ".", ""]);
assertEquals(split("1.2,3...4,5.", /[,\.]*/), ["1", "", "", ".", "2", "", "", ",", "3", "", "", "...", "4", "", "", ",", "5", "", "", ".", ""]);
assertEquals(split("1.2,3...4,5.", /[,\.]/g), ["1", ".", "2", ",", "3", ".", "", ".", "", ".", "4", ",", "5", ".", ""]);
assertEquals(split("1.2,3...4,5.", /[,\.]+/g), ["1", ".", "2", ",", "3", "...", "4", ",", "5", ".", ""]);
assertEquals(split("1.2,3...4,5.", /[,\.]*/g), ["1", "", "", ".", "2", "", "", ",", "3", "", "", "...", "4", "", "", ",", "5", "", "", ".", ""]);

// quick and dirty assert check
function assertEquals(actual, expected) {
  console.log(JSON.stringify(actual) === JSON.stringify(expected));
}

Solution 8 - Javascript

function split2(original){
   var delimiter = "d", result = [], tmp;
   tmp = original.split(delimiter);
   tmp.forEach(function(x){result.push(x); result.push(delimiter); });
   return result;
}

Solution 9 - Javascript

Try this

"abcdeabcde".split("d").reduce((result, value, index) => {
    return (index !== 0) ? result.concat(["d", value]) : result.concat(value)
}, [])

Solution 10 - Javascript

Try this

var string = "abcdeabcde";
var res = string.replace( /d/g, 'd\0' ).split(/(?=d)|\0/);
console.log( res );
//["abc", "d", "eabc", "d", "e"]

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMartin JaniczekView Question on Stackoverflow
Solution 1 - JavascriptKaiView Answer on Stackoverflow
Solution 2 - JavascriptmichaView Answer on Stackoverflow
Solution 3 - JavascriptInfoLearnerView Answer on Stackoverflow
Solution 4 - JavascriptbobinceView Answer on Stackoverflow
Solution 5 - Javascriptudn79View Answer on Stackoverflow
Solution 6 - JavascriptChanduView Answer on Stackoverflow
Solution 7 - JavascriptEbrahim ByagowiView Answer on Stackoverflow
Solution 8 - Javascriptpc1oad1etterView Answer on Stackoverflow
Solution 9 - Javascriptheesu SuhView Answer on Stackoverflow
Solution 10 - JavascriptmeouwView Answer on Stackoverflow