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) ];
3
  • 1
    Dupe doesn't look like what OP is looking for here as OP already knows how to use slice or substring Commented Oct 19, 2022 at 6:45
  • 1
    @anubhava The accepted answer with the highest vote-count is the same as your "Alternative" o.O Commented Oct 19, 2022 at 7: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. Commented Oct 19, 2022 at 7:50

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

-1

You can do it like this

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.