Hi Friends đź‘‹,

Welcome To Infinitbility! ❤️

To split first 4 characters of string in javascript, use substring(0, 4) it will return first 4 characters of string and if want another part of the string use substring(4, string.length) and it will return the else part of string.

Let’s see short example of javascript get the first 4 characters of the string.

const string = "0001infinitbility";
const first4Char = string.substring(0, 4);

console.log(first4Char)

Today, I’m going to show you How do I split string’s first 4 characters in javascript, as mentioned above, I’m going to use the above-mentioned substring() method.

Let’s start today’s tutorial how do you split string’s first 4 characters in javascript.

Javascript split string first 4 characters

Here, we will get first 4 characters of the string, then the rest string and then we will create an array of those values because split always returns an array.

const string = "0001infinitbility";
const first4Char = string.substring(0, 4);
const restString = string.substring(4, string.length);

const splitArray = [first4Char, restString]


console.log("first4Char", first4Char);
console.log("restString", restString);
console.log("splitArray", splitArray);

// Output:
// first4Char 0001
// restString infinitbility
// splitArray [ '0001', 'infinitbility' ]

Output

I hope it helps you, All the best đź‘Ť.