sgmonda
sgmonda

Reputation: 2729

Split string by index in JavaScript using direct way like splitting by a regex

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

Upvotes: 1

Views: 1553

Answers (2)

anubhava
anubhava

Reputation: 785316

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.

Upvotes: 3

boki_bo
boki_bo

Reputation: 80

You can do it like this

const splitAt = (index, input) => [input.slice(0, index), input.slice(index)]

Upvotes: -1

Related Questions