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

Answers:

Answer

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.

Answer
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.)

Answer

Can be done in one line:

var string = "abcdeabcde";    
string.split(/(d)/);
["abc", "d", "eabc", "d", "e"]
Answer

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".

Answer

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));
}
Answer

Just override the String.prototype.split function with this one :

String.prototype._split = String.prototype.split;
String.prototype.split = function(delimiter, keepDelimiters) {
    if (!keepDelimiters) {
        return this._split(delimiter);
    } else {
        var res = [];
        var start = 0, index;
        while ((index = this.indexOf(delimiter, start)) != -1) {
            res.push(this.substr(start, index - start));
            res.push(delimiter);
            start = index + 1;
        }
        res.push(this.substr(start));
        return res;
    }
};


var str = "abcdeabcde";
alert(str.split("d", true));
alert(str.split("d"));

// output : 
//
//  [ 'abc', 'd', 'eabc', 'd', 'e' ]
//  [ 'abc', 'eabc', 'e' ]

This method will not fail, do not use regular expressions and is consistent with the original String.split function. It is also consistent with the str.split(/(d)/); solution, but will not fail in IE.

The only restriction is that, if the second parameter is used (the split replacement drop-in function), then the delimiter cannot be a regular expression. But if you think about it a little, it's not a real restriction since you don't need the second parameter if using regular expression...

Answer

Try:

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

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.

Answer

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);
    }
Answer

Try this

"abcdeabcde".split("d").reduce((result, value, index) => {
    return (index !== 0) ? result.concat(["d", value]) : result.concat(value)
}, [])
Answer
function split2(original){
   var delimiter = "d", result = [], tmp;
   tmp = original.split(delimiter);
   tmp.forEach(function(x){result.push(x); result.push(delimiter); });
   return result;
}
Answer

Try this

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.