slice string based on hyphen in javascript

To slice a string based on hyphen in JavaScript, you can use the String.prototype.slice() method with the indexOf() and lastIndexOf() methods to find the positions of the hyphens.

Here's an example:

index.tsx
const str = "apple-banana-orange";
const firstHyphenIndex = str.indexOf("-");
const lastHyphenIndex = str.lastIndexOf("-");
const slicedString = str.slice(firstHyphenIndex + 1, lastHyphenIndex);

console.log(slicedString); // "banana"
235 chars
7 lines

In this example, we first define our string as str. We then use the indexOf() method to find the first occurrence of the hyphen in the string and store its index in the firstHyphenIndex variable.

Next, we use the lastIndexOf() method to find the last occurrence of the hyphen in the string and store its index in the lastHyphenIndex variable.

Finally, we use the slice() method to extract the substring between the first hyphen and the last hyphen (excluding them) and store it in the slicedString variable, which we then log to the console.

This will output "banana", which is the string between the first and last hyphens in our original string.

related categories

gistlibby LogSnag