For your specific case where you just want two parts, the simplest thing is indexOf
and substring
:
const index = text.indexOf("_");
const p0 = index === -1 ? text : text.substring(0, index);
const p1 = index === -1 ? "" : text.substring(index + 1);
Live Example:
const text = "hello_world_there";
const index = text.indexOf("_");
const p0 = index === -1 ? text : text.substring(0, index);
const p1 = index === -1 ? "" : text.substring(index + 1);
console.log(`p0 = "${p0}", p1 = "${p1}"`);
I've found I want that often enough I have it in a utility module:
const twoParts = (str, delim = " ") => {
const index = str.indexOf("_");
if (index === -1) {
return [str, ""];
}
return [
str.substring(0, index),
str.substring(index + delim.length),
];
};
But if you wanted to do more than just teh two parts, an approach that doesn't require rejoining the string after the fact would be to use a regular expression with capture groups:
const result = text.match(/^([^_]+)_+([^_]+)_+(.*)$/);
const [_, p0 = "", p1 = "", p2 = ""] = result ?? [];
Live Example:
const text = "hello_world_xyz_there";
const result = text.match(/^([^_]+)_+([^_]+)_+(.*)$/);
const [_, p0 = "", p1 = "", p2 = ""] = result ?? [];
console.log(`p0 = "${p0}", p1 = "${p1}", p2 = "${p2}"`);