slice string based on hyphen and select second one in javascript

You can use the split() method and array indexing to achieve this:

index.tsx
const str = "first-second-third";
const second = str.split("-")[1];
console.log(second); // output: "second"
109 chars
4 lines

Alternatively, you can use the substr() method to extract the second part of the string based on the index of the hyphen:

index.tsx
const str = "first-second-third";
const second = str.substr(str.indexOf("-") + 1, str.length);
console.log(second); // output: "second-third"
142 chars
4 lines

Note that if your string contains multiple hyphens and you want to always select the second part, you can use a regular expression to match the second group of non-hyphen characters:

index.tsx
const str = "first-second-third";
const second = str.match(/-([^-\s]+)-/)[1];
console.log(second); // output: "second"
119 chars
4 lines

gistlibby LogSnag