Home  >  Article  >  Web Front-end  >  How can I remove the last character from a string in JavaScript?

How can I remove the last character from a string in JavaScript?

Susan Sarandon
Susan SarandonOriginal
2024-10-25 13:33:02508browse

How can I remove the last character from a string in JavaScript?

Trimming the Last Character from a String in JavaScript

In certain scenarios, you may encounter the need to remove the last character from a string. JavaScript offers several methods to achieve this.

One efficient solution is to utilize the substring() function. This method allows you to extract a portion of a string based on the specified indices. By providing the correct parameters, you can exclude the last character.

For instance, let's consider the string "12345.00". To trim the last character (which is 0), we can use the following code:

<code class="javascript">let str = "12345.00";
str = str.substring(0, str.length - 1);
console.log(str);</code>

This will output "12345.0", as the last character has been removed.

The key to using substring() effectively is to specify the correct indices. In this case, providing 0 as the starting index includes the first character, and specifying str.length - 1 as the ending index excludes the last character.

The above is the detailed content of How can I remove the last character from a string in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn