mdawar.dev

A blog about programming, Web development, Open Source, Linux and DevOps.

Remove Last Character from String in JavaScript

To remove the last character from a string in JavaScript we can use the slice() method which extracts a section of a string without modifying it.

Use a start index of 0 (the first character) and a negative end index -1 to count from the end of the string.

js
const site = 'https://example.com/';

/**
 * slice(indexStart, indexEnd)
 *
 * 0 is the start index (first character)
 * -1 is the end index (counted from the end of the string when negative)
 */
const withoutSlash = site.slice(0, -1); // 'https://example.com'

To remove multiple characters just change the end index.

js
'ABCD'.slice(0, -2); // 'AB'