Skip to content

Remove first and the last character from string JavaScript

  • by

Use slice() method, passing it 1 and -1 as parameters to Remove the first and the last character from the string in JavaScript. This method returns a new string containing the extracted section from the original string.

slice(beginIndex, endIndex)
string.slice(1, -1)

An alternative approach to removing the characters from a string is to use the substring method.

substring(indexStart, indexEnd)
yourString.substring(1, yourString.length-1);

Note: Both methods do not modify the original string.

Remove first and the last character from string JavaScript

Simple example code.

<!DOCTYPE html>
<html>
<body>

  <script>
    const str = 'ABCD';
    console.log(str);

    // slice
    const res = str.slice(1, -1);
    console.log(res);

    // substring
    const nres = str.substring(1, str.length - 1);
    console.log(nres);

  </script>

</body>
</html>

Output:

Remove first and the last character from string JavaScript

if you need to remove the first letter of the string

string.slice(1, 0)

and for removing the last letter

string.slice(0, -1)

Delete the first character of the string if it is 0

You can remove the first character of a string using substring:

var s1 = "foobar";
var s2 = s1.substring(1);
alert(s2); // shows "oobar"

To remove all 0’s at the start of the string:

var s = "0000test";
while(s.charAt(0) === '0')
{
 s = s.substring(1);
}

Source: stackoverflow.com

Do comment if you have any doubts or suggestions on this Js remove char topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *