Javascript JS string.split() 不删除分隔符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4514144/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 12:44:28  来源:igfitidea点击:

JS string.split() without removing the delimiters

javascriptsplitdelimiter

提问by Martin Janiczek

How can I split a string without removing the delimiters?

如何在不删除分隔符的情况下拆分字符串?

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

假设我有一个字符串: var string = "abcdeabcde";

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

当我这样做时 var newstring = string.split("d"),我得到这样的东西:

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

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

But I want to get this:

但我想得到这个:

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

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

当我尝试执行“split2”函数时,我陷入了 splice() 和索引以及“this”与“that”之间的纠缠……啊!帮助!:D

采纳答案by InfoLearner

Try this:

尝试这个:

  1. Replace all of the "d" instances into ",d"
  2. Split by ","
  1. 将所有“d”实例替换为“,d”
  2. 用“,”分割
var string = "abcdeabcde";
var newstringreplaced = string.replace(/d/gi, ",d");
var newstring = newstringreplaced.split(",");
return newstring;

Hope this helps.

希望这可以帮助。

回答by Kai

Try:

尝试:

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

回答by micha

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 Assertionin regex, which makes a match not part of the capture group. No other tricks or workarounds needed.

这是在正则表达式中使用前瞻零长度断言,这使得匹配不属于捕获组。不需要其他技巧或解决方法。

回答by bobince

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

(反向循环是必要的,以避免将ds添加到已d插入 s的列表部分。)

回答by JonMayer

Can be done in one line:

可以在一行中完成:

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

回答by udn79

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

split - split 用于创建不用于搜索的单独行。

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

[^d] - 找到一组不包含“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".

如果您不希望“javascript”出现问题,请阅读“RegExp Object”。

回答by Ebrahim Byagowi

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.

这是我的正则表达式分隔符版本。它与 String.prototype.split 具有相同的接口;它将毫无区别地对待全局和非全局正则表达式。返回值是一个数组,它的奇数成员是匹配的分隔符。

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

回答by Chandu

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

回答by heesu Suh

Try this

尝试这个

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

回答by pc1oad1etter

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