skip to Main Content

Let’s say I have this value ‘BERNY564567JH89E’. How would I split the value into different strings, after the 11th character, which in this case would be 7. So for example, in the end I would have the following returned:

const orignalValue = "BERNY564567JH89E"

const splitValueOne = "BERNY564567"
const splitValueTwo = "JH89E"

2

Answers


  1. You can match with a regex and limit your count using {11}.

    const
      orignalValue = 'BERNY564567JH89E',
      [match, group1, group2] = orignalValue.match(/([a-z0-9]{11})([a-z0-9]*)/i) ?? [];
    
    console.log({ group1, group2 }); // { "group1": "BERNY564567", "group2": "JH89E" }

    Here is a function that uses String.prototype.slice:

    const
      orignalValue = 'BERNY564567JH89E',
      splitAtIndex = (str, index) => [str.slice(0, index), str.slice(index + 1)],
      [head, tail] = splitAtIndex(orignalValue, 11);
    
    console.log({ head, tail }); // { "head": "BERNY564567", "tail": "JH89E" }
    Login or Signup to reply.
  2. You can easily reach the desired result using substring() function:

    const originalValue = "BERNY564567JH89E";
    const splitValueOne = originalValue.substring(0, 11);
    const splitValueTwo = originalValue.substring(11);
    

    Or slice() as an option:

    const originalValue = "BERNY564567JH89E";
    const [splitValueOne, splitValueTwo] = [
      originalValue.slice(0, 11),
      originalValue.slice(11)
    ];
    

    The only difference between these methods that you can concern about is the way they process negative values: substring() treats them as zeros while slice() makes an offset from the end of the string. Since 11 is a positive digit, it won’t make any difference for you.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search