Languages
[Edit]
EN

JavaScript - remove last 2 characters from string

0 points
Created by:
Admin Dirask Community
1420

In this article, we're going to have a look at how to remove last 2 characters from string in JavaScript.

1. String slice() method example

This approach allows to get substring by using negative indexes. So by using 0 and -2 indexes as range we get <0, text.length - 2> text range. 

// ONLINE-RUNNER:browser;

var text = 'abcde';
var substring = text.slice(0, -2);

console.log(substring); // abc

2. String substring() method example

This is alternative approach to slice method based solution.

// ONLINE-RUNNER:browser;

var text = 'abcde';
var substring = text.substring(0, text.length - 2);

console.log(substring); // abc

3. String replace() method example

There is another trick that allows to replace all characters that match rexpression condition. By using .{0,2}$ pattern we match all any 2 characters (up to 2 characters) that are loacated at the end of string.

// ONLINE-RUNNER:browser;

var text = 'abcde';
var substring = text.replace(/.{0,2}$/, '');

console.log(substring); // abc

JavaScript - String (popular problems)

JavaScript - remove last 2 characters from string
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

â€ïžđŸ’» 🙂

Join