Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/460.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 仅在分隔符的前n个位置拆分字符串_Javascript - Fatal编程技术网

Javascript 仅在分隔符的前n个位置拆分字符串

Javascript 仅在分隔符的前n个位置拆分字符串,javascript,Javascript,我只希望在分隔符的前n个位置拆分字符串。我知道,我可以使用一个循环将它们添加到一起,但是没有更直接的方法吗 var string = 'Split this, but not this'; var result = new Array('Split', 'this,', 'but not this'); JavaScript“.split()”函数已经接受了第二个参数,该参数给出了要执行的最大拆分次数。但是,它不会保留原始字符串的尾端;你得把它粘回去 另一种方法是使用正则表达式迭代地删

我只希望在分隔符的前n个位置拆分字符串。我知道,我可以使用一个循环将它们添加到一起,但是没有更直接的方法吗

var string = 'Split this, but not this';    
var result = new Array('Split', 'this,', 'but not this');
JavaScript“.split()”函数已经接受了第二个参数,该参数给出了要执行的最大拆分次数。但是,它不会保留原始字符串的尾端;你得把它粘回去

另一种方法是使用正则表达式迭代地删除字符串的前导部分,在达到限制时停止

var str = "hello out there cruel world";
var parts = [];
while (parts.length < 3) { // "3" is just an example
  str = str.replace(/^(\w+)\s*(.*)$/, function(_, word, remainder) {
    parts.push(word);
    return remainder;
  });
}
parts.push(str);
var str=“你好,外面是残酷的世界”;
var部分=[];
而(parts.length<3){/“3”只是一个例子
str=str.replace(/^(\w+)\s*(.*)$/,函数(508;,字,余数){
零件。推(字);
返回剩余部分;
});
}
零件。推(str);

编辑-我突然想到,另一个简单的方法是只使用普通的“.split()”,去掉前几个部分,然后只使用“.slice()”和“.join()”,剩下的部分。

虽然你可以给
split
一个限制,但你不会得到你所说的你想要的。不幸的是,您将不得不在这一点上自己动手,例如:

var string = 'Split this, but not this';
var result = string.split(' ');

if (result.length > 3) {
    result[2] = result.slice(2).join(' ');
    result.length = 3;
}
但即便如此,最终还是要修改它后面部分的空格数。因此,我可能会采用老式的编写自己的循环方式:

function splitWithLimit(str, delim, limit) {
  var index,
      lastIndex = 0,
      rv = [];

  while (--limit && (index = str.indexOf(delim, lastIndex)) >= 0) {
    rv.push(str.substring(lastIndex, index));
    lastIndex = index + delim.length;
  }
  if (lastIndex < str.length) {
    rv.push(str.substring(lastIndex));
  }
  return rv;
}
函数splitWithLimit(str、delim、limit){
var指数,
lastIndex=0,
rv=[];
而(-limit&&(index=str.indexOf(delim,lastIndex))>=0){
rv.push(str.substring(lastIndex,index));
lastIndex=索引+delim.length;
}
if(lastIndex

根据:

更新:

var string = 'Split this, but not this',
    arr = string.split(' '),
    result = arr.slice(0,2);

result.push(arr.slice(2).join(' ')); // ["Split", "this,", "but not this"]
var string = 'Split this, but not this',
    arr = string.split(' '),
    result = arr.splice(0,2);

result.push(arr.join(' ')); // result is ["Split", "this,", "but not this"]
更新版本2(一个
片段
更短):

var string = 'Split this, but not this',
    arr = string.split(' '),
    result = arr.slice(0,2);

result.push(arr.slice(2).join(' ')); // ["Split", "this,", "but not this"]
var string = 'Split this, but not this',
    arr = string.split(' '),
    result = arr.splice(0,2);

result.push(arr.join(' ')); // result is ["Split", "this,", "but not this"]

为此,您可以使用拆分(分隔符)并选择一个分隔符

var testSplit = "Split this, but not this";
var testParts= testSplit.Split(",");

var firstPart = testParts[1];

// firstPart = "Split this"
我的语法不是100%,我已经有一段时间没有使用javascript了。但我知道这是怎么做到的

对不起,我弄错了。现在我相信我知道你的要求,我认为最简单的方法是使用substr。非常简单,不需要循环。只是做了个例子,效果很好

// so first, we want to get everything from 0 - the first occurence of the comma.
// next, we want to get everything after the first occurence of the comma.  (if you only define one parameter, substr will take everything after that parameter.

var testString = "Split this, but this part, and this part are one string";
var part1 = testString.substr(0,testString.indexOf(',')); 
var part2 = testString.substr(testString.indexOf(','));

//part1 = "Split this"
//part2= "but this part, and this part are one string"
使用Array.slice发出警报['Split','this','但不是this']

function splitWithTail(str,delim,count){
  var parts = str.split(delim);
  var tail = parts.slice(count).join(delim);
  var result = parts.slice(0,count);
  result.push(tail);
  return result;
}
结果:

splitWithTail(string," ",2)
// => ["Split", "this,", "but not this"]

您好,我遇到了同样的问题,我只想拆分几次,找不到任何东西,所以我只是扩展了DOM-只是一个快速而肮脏的解决方案,但它可以工作:)


sane
limit
实现的改进版本,并提供适当的正则表达式支持:

function splitWithTail(value, separator, limit) {
    var pattern, startIndex, m, parts = [];

    if(!limit) {
        return value.split(separator);
    }

    if(separator instanceof RegExp) {
        pattern = new RegExp(separator.source, 'g' + (separator.ignoreCase ? 'i' : '') + (separator.multiline ? 'm' : ''));
    } else {
        pattern = new RegExp(separator.replace(/([.*+?^${}()|\[\]\/\\])/g, '\\$1'), 'g');
    }

    do {
        startIndex = pattern.lastIndex;
        if(m = pattern.exec(value)) {
            parts.push(value.substr(startIndex, m.index - startIndex));
        }
    } while(m && parts.length < limit - 1);
    parts.push(value.substr(pattern.lastIndex));

    return parts;
}

为Chrome、Firefox、Safari、IE8+构建并测试。

我刚刚写的另一个实现:

export function split(subject, separator, limit=undefined, pad=undefined) {
    if(!limit) {
        return subject.split(separator);
    }
    if(limit < 0) {
        throw new Error(`limit must be non-negative`);
    }
    let result = [];
    let fromIndex = 0;
    for(let i=1; i<limit; ++i) {
        let sepIdx = subject.indexOf(separator, fromIndex);
        if(sepIdx < 0) {
            break;
        }
        let substr = subject.slice(fromIndex, sepIdx);
        result.push(substr);
        fromIndex = sepIdx + separator.length;
    }
    result.push(subject.slice(fromIndex));
    while(result.length < limit) {
        result.push(pad);
    }
    return result;
}
结果:

["Split", "this, but not this"]

我喜欢使用
shift

function splitFirstN(str,n,delim){
    var parts = str.split(delim);
    var r = [];
    for(var i = 0; i < n; i++){
        r.push(parts.shift());
    }
    r.push(parts.join(delim));
    return r;
}

var str = 'Split this, but not this';    
var result = splitFirstN(str,2,' ');
函数splitFirstN(str,n,delim){
变量部分=str.split(delim);
var r=[];
对于(变量i=0;i
拆分
加入
与ES6功能相结合,这一点非常巧妙:

let [str1, str2, ...str3] = string.split(' ');
str3 = str3.join(' ');

没有什么是一个简单的正则表达式不能做到的:

const string='splitthis,但不是this';

console.log(string.match(/^(\S+)\S*(\S+)?\S*([\S\S]+)?$/).slice(1))在我的例子中,我试图解析git grep stdout。所以我有一个{filename}:{linenumber}:{context}。我不喜欢先分裂后加入。我们应该能够一次性解析字符串。你可以简单地一步一步地浏览每个字母,并在前两个冒号上分开。一种开箱即用的快速方法是使用match方法和regex

因此,

txt.match(/(.+):(\d+):(.*)/)


非常好

又是一个有限制的实现

// takes string input only
function split(input, separator, limit) {
    input = input.split(separator);
    if (limit) {
        input = input.slice(0, limit - 1).concat(input.slice(limit - 1).join(separator));
    }
    return input;
}

我的通用版本支持RegExp和非RegExp分隔符。高度优化。提供了测试。 原因:因为其他RegExp版本都充满了bug,这不是一个简单的函数

用法

"a b  c   d".split_with_tail(/ +/,3) = ['a','b','c   d']
"a b  c   d".split_with_tail(' ',3) = ['a','b',' c   d']
代码

String.prototype.split_with_tail = function(delimiter,limit)
{
    if( typeof(limit) !== 'number' || limit < 1 ) return this.split(delimiter,limit);

    var parts = this.split(delimiter,limit+1);
    if( parts.length <= limit ) return parts;
    parts.splice(-2,2);

    limit = Math.floor(limit) - 1; // used later as index, speed optimization; limit can be float ..
    if( delimiter instanceof RegExp ) {
        // adds 'g' flag to any regexp:
        delimiter += '';
        var len = delimiter.lastIndexOf('/');
        delimiter = new RegExp(delimiter.slice(1, len), delimiter.slice(len + 1)+'g');

        len = 0;
        while(limit--) len += parts[limit].length + (delimiter.exec(this))[0].length;
    }
    else {
        var len = limit * (''+delimiter).length;
        while(limit--) len += parts[limit].length;
    }

    parts.push(this.substring(len)); // adds tail, finally
    return parts;
}
ES2015
复杂性O(n)。

在我的例子中,这解决了我的问题:

const splitted = path.split('/')
const core = splittedPath.slice(0, 2)
const rest = splittedPath.slice(2).join('/')
const result = [...core, rest]

事实上,没有。他会回来的,不是他要求的。
split
的限制出乎意料地无用,与许多其他
split
函数不同。是的@TJ,这就是为什么我添加了关于粘上“尾巴”的警告。我刚才发表评论时没有注意到。:-)等等,也许是。我的编辑技巧又来了!是的,它的工作方式非常令人惊讶。这将删除第三部分。嗨,大卫。你的回答帮助了我。你怎么看:
var string='splitthis,而不是this',result=string.Split(“”),result.push(result.splice(2.join(“”))?虽然简洁,但这不能处理字符串只有一个空格的情况-结果数组将包含一个额外的空字符串。@riv Good point。对于其他任何人来说,如果
arr.length>0
,只需按最后一部分即可解决此问题。在本例中,它会起作用,但实际上可能会在以后出现更多逗号等。@nines但这不是您要做的吗?“仅在分隔符的前n次出现时才出现”我的示例很愚蠢,抱歉。实际上我有一个简单的协议:
command+delimiter+options+delimiter+data
。前两部分是固定的,因此不会有字符,但数据部分长度可变,可以包含任何内容。我只是想有一个简短的标准方法来实现这一点,因为javascript split似乎不同于其他一些语言,它切断了其余部分,而不是将其放入其他元素中。@nines您可以编辑您的问题,并发布一个带有真实字符串和预期输出的示例。请参阅我的最新编辑,我想这正是你想要的。可能的复制品很好!但要注意IE和Safari中的兼容性:请参阅覆盖
let [str1, str2, ...str3] = string.split(' ');
str3 = str3.join(' ');
// takes string input only
function split(input, separator, limit) {
    input = input.split(separator);
    if (limit) {
        input = input.slice(0, limit - 1).concat(input.slice(limit - 1).join(separator));
    }
    return input;
}
"a b  c   d".split_with_tail(/ +/,3) = ['a','b','c   d']
"a b  c   d".split_with_tail(' ',3) = ['a','b',' c   d']
String.prototype.split_with_tail = function(delimiter,limit)
{
    if( typeof(limit) !== 'number' || limit < 1 ) return this.split(delimiter,limit);

    var parts = this.split(delimiter,limit+1);
    if( parts.length <= limit ) return parts;
    parts.splice(-2,2);

    limit = Math.floor(limit) - 1; // used later as index, speed optimization; limit can be float ..
    if( delimiter instanceof RegExp ) {
        // adds 'g' flag to any regexp:
        delimiter += '';
        var len = delimiter.lastIndexOf('/');
        delimiter = new RegExp(delimiter.slice(1, len), delimiter.slice(len + 1)+'g');

        len = 0;
        while(limit--) len += parts[limit].length + (delimiter.exec(this))[0].length;
    }
    else {
        var len = limit * (''+delimiter).length;
        while(limit--) len += parts[limit].length;
    }

    parts.push(this.substring(len)); // adds tail, finally
    return parts;
}
function test(str,delimiter,limit,result) {
    if( JSON.stringify(result) !== JSON.stringify(str.split_with_tail(delimiter,limit)) ) {
        console.log(arguments);
        console.log(str.split_with_tail(delimiter,limit));
        throw "lol";
    }
}
test('',/ +/,undefined,['']);
test('',/ +/,3,['']);
test('a',/ +/,0.1,[]);
test('a',/ +/,1,['a']);
test('a a',/ +/,1,['a a']);
test('a a',/ +/,2.1,['a','a']);
test('a a a',/ +/,2.9,['a','a a']);
test('aaaaa aa a',/ +/,1,['aaaaa aa a']);
test('aaaaa aa a',/ +/,2,['aaaaa', 'aa a']);
test('a a',/ +/,2,['a','a']);
test('a',/ +/,3,['a']);
test('a a',/ +/,3,['a','a']);
test('a a  a',/ +/,3,['a','a','a']);
test('a a  a  a',/ +/,3,['a','a','a  a']);
test('a a  a  a',/ +/,4,['a','a','a','a']);
test('a aa  aaa  ',/ +/,4,['a','aa','aaa','']);
test('a a  a  a',/ +/,2,['a','a  a  a']);
test('a a  a  a',/ +/,1,['a a  a  a']);
test('a a  a  a',/ +/,0,[]);
test('a a  a  a',/ +/,undefined,['a','a','a','a']);
test('a a  a  a',/ +/,-1,['a','a','a','a']);

test('a',' ',3,['a']);
test('aaaaa aa a',' ',2,['aaaaa', 'aa a']);
test('aaaaa  aa  a','  ',2,['aaaaa','aa  a']);
test('a a a',' ',3,['a','a','a']);
test('a a a a',' ',3,['a','a','a a']);
test('a a  a a',' ',3,['a','a',' a a']);
test('a a  a a',' ',2,['a','a  a a']);
test('a a  a a',' ',1,['a a  a a']);
test('a a  a a',' ',0,[]);
test('a a  a a',' ',undefined,['a','a','','a','a']);
test('a a  a a',' ',-1,['a','a','','a','a']);
test('1232425',2,3,['1','3','425']);
console.log("good!");
const splitAndAppend = (str, delim, count) => {
    const arr = str.split(delim);
    return [...arr.splice(0, count), arr.join(delim)];
}
const splitted = path.split('/')
const core = splittedPath.slice(0, 2)
const rest = splittedPath.slice(2).join('/')
const result = [...core, rest]