skip to Main Content
let text = "testing: 1, 2, 3";
console.log(text.split(/D+/));

Output:
["", "1", "2", "3"]

why "testing:" is not the first element? "testing:" is also non-digit like space. What is the logic behind first element as empty string?

4

Answers


  1. To make it easier to understand:

    let text = "text";
    console.log(text.split(/D+/));

    The explanation: since the delimiter is found in the string so it definitely can split the string, despite of the result being 2 empty strings.

    Login or Signup to reply.
  2. .split() divides a string by removing the matching substrings.

    In your case:

    testing: 1, 2, 3
    ^^^^^^^^^ ^^ ^^
    
    Login or Signup to reply.
  3. Prefer to use match

    let text = "testing: 1, 2, 3";
    console.log( text.match(/(d+)/g) );
    Login or Signup to reply.
  4. It’s about how delimiters at the beginning or end of a string are handled.

    First understand that D+ matches the following strings in testing: 1, 2, 3

    • testing:
    • ,
    • ,

    Those are now the delimiters. What’s before the first delimiter is "" and what’s after the last delimiter is 3

    When the delimiter is at the beginning or end of a string, then split will return an empty element before the initial delimiter or after the final delimeter.

    Refer to the documentation

    If separator appears at the beginning (or end) of the string, it still has the effect of splitting, resulting in an empty (i.e. zero length) string appearing at the first (or last) position of the returned array. If separator does not occur in str, the returned array contains one element consisting of the entire string.

    This is important because if you had a data file with name, street in comma-separated value (CSV) format and you split a line that looked like ,main you would expect that name = "" and street = main. "Where the street has no name." 😉

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