How to Split String Only On First Character Occurrence in JavaScript


I was working with a key-value store that was segmented by namespaces.

This meant that keys were organized and grouped to prevent name collisions, which is especially helpful when my code is used by multiple applications or my code uses multiple libraries.

For instance, a key-value store used by two projects (p1, p2) might look like this:

{
    "p1:username": "johndoe",
    "p1:color": "black",
    "p2:username": "joedoe",
    "p2:color": "blue"
}

I needed a way to separate the namespace and the key itself.

let namespacedKey = "p1:username";
namespacedKey.substring(0, namespacedKey.indexOf(":")); // "p1"
namespacedKey.substring(namespacedKey.indexOf(":") + 1); // "username"

This also works with multiple occurrences of the separator.

let namespacedKey = "p1:user:name";
namespacedKey.substring(0, namespacedKey.indexOf(":")); // "p1"
namespacedKey.substring(namespacedKey.indexOf(":") + 1); // "user:name"