1

This is kind of a challenge, as I'm sure there must be a better way to do this but I'm not able to find it.

Given a string, I want to split it into two strings by a given index. For instance:

input: 
  - string: "helloworld"
  - index: 5
output: ["hello", "world"]

An easy way is to make two slices, but isn't there a more direct way like splitting by a regex or something? I would like to achieve my purpose with a single instruction.

The non-elegant way:

const str = "helloworld";
const [ str1, str2 ] = [ str.substring(0, 5), str.substring(5) ];
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
sgmonda
  • 2,615
  • 1
  • 19
  • 29
  • 1
    Dupe doesn't look like what OP is looking for here as OP already knows how to use `slice` or `substring` – anubhava Oct 19 '22 at 06:45
  • 1
    @anubhava The accepted answer with the highest vote-count is the same as your _"Alternative"_ o.O – Andreas Oct 19 '22 at 07:22
  • 1
    But it is not the main solution which is using `split` besides IMO dupe marking has to be on the nature of the problem not the similarity of an answer. – anubhava Oct 19 '22 at 07:50

2 Answers2

3

You can use this regex for splitting:

(?<=^.{5})

Here (?<=^.{5}) is a lookbehind assertion that splits at the position that has 5 characters on left hand side after start.

Code:

var s = 'helloworld';

var arr = s.split(/(?<=^.{5})/);

console.log(arr);
//=> ['hello', 'world']

Alternatively, you can use match + slice:

s.match(/^(.{5})(.*)/).slice(1)

We must use .slice(1) here to discard first element of array which is full match.

anubhava
  • 761,203
  • 64
  • 569
  • 643
-1

You can do it like this

const splitAt = (index, input) => [input.slice(0, index), input.slice(index)]
boki_bo
  • 80
  • 9