在给定索引上将字符串拆分为两个并返回两个部分

Mik*_*gin 57 javascript

我有一个字符串,我需要在给定的索引上拆分,然后返回两个部分,用逗号分隔.例如:

string: 8211 = 8,211
        98700 = 98,700
Run Code Online (Sandbox Code Playgroud)

所以我需要能够在任何给定的索引上拆分字符串,然后返回字符串的两半.内置方法似乎执行拆分但只返回拆分的一部分.

string.slice只返回提取的字符串部分.string.split只允许你拆分字符而不是索引string.substring做我需要但只返回子串string.substr非常相似 - 仍然只返回子串

Cha*_*mal 85

试试这个

function splitValue(value, index) {
    return value.substring(0, index) + "," + value.substring(index);
}

console.log(splitValue("3123124", 2));
Run Code Online (Sandbox Code Playgroud)

  • 问题要求分为两部分.你不应该返回`[value.substring(0,index),value.substring(index)]`? (4认同)

Ala*_*res 41

ES6 1线

// :: splitAt = number => Array<any>|string => Array<Array<any>|string>
const splitAt = index => x => [x.slice(0, index), x.slice(index)]

console.log(
  splitAt(1)('foo'), // ["f", "oo"]
  splitAt(2)([1, 2, 3, 4]) // [[1, 2], [3, 4]]
)
  
Run Code Online (Sandbox Code Playgroud)


lon*_*556 6

您可以轻松扩展它以拆分多个索引,并采用数组或字符串

const splitOn = (slicable, ...indices) =>
  [0, ...indices].map((n, i, m) => slicable.slice(n, m[i + 1]));

splitOn('foo', 1);
// ["f", "oo"]

splitOn([1, 2, 3, 4], 2);
// [[1, 2], [3, 4]]

splitOn('fooBAr', 1, 4);
//  ["f", "ooB", "Ar"]
Run Code Online (Sandbox Code Playgroud)

lodash 问题跟踪器:https : //github.com/lodash/lodash/issues/3014