How to Extract a Substring Except the Last Character in JavaScript?

Estimated read time 1 min read

To extract a substring except the last character in JavaScript, you can use the String.slice() method. Here’s an example:

const string = "Hello, world!";
const substring = string.slice(0, -1);
console.log(substring); // Output: "Hello, world"

Here’s what the String.slice() method does:

  • The first argument (0) is the index where the slice starts.
  • The second argument (-1) is the index where the slice ends. Using a negative number means the slice ends that many characters from the end of the string, so -1 means the slice ends at the second to last character.
  • The method returns a new string that includes all characters from the start index up to, but not including, the end index.

In this example, substring will contain the entire string except for the last character, which is the exclamation mark.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply