Languages
[Edit]
EN

JavaScript - remove first 2 characters from string

0 points
Created by:
Elmer-Li
516

In JavaScript, it is possible to remove the first 2 characters from the string in the following ways.

1. Using String slice() method

// ONLINE-RUNNER:browser;

var text = '12345';
var substring = text.slice(2);

console.log(substring); // 345

In the second example, we can see that we can also use a string slice on the empty or shorter string than 2 characters (or in case we want to remove n characters from our string).

// ONLINE-RUNNER:browser;

// true means string is empty
console.log(''.slice(2) === ''); // empty
console.log('1'.slice(2) === ''); // empty
console.log('12'.slice(2) === ''); // empty
console.log('123'.slice(2)); // 3
console.log('1234'.slice(2)); // 34
console.log('12345'.slice(2)); // 345

We use ''.slice(2) === '' to see that the string after the slice operation is empty.

An empty result means that string was shorter than 2 characters or the length was exactly 2 characters and our string is empty (the length of the string is 0).

Because string slice returns string then we can also call string length method to check the size of the returned string, like on below example:

// ONLINE-RUNNER:browser;

console.log(''.slice(2) === ''); // empty
console.log(''.slice(2).length); // 0

2. Using String substring() method

// ONLINE-RUNNER:browser;

var text = '1234';
var substring = text.substring(2);

console.log(substring); // 34

3. Using String replace() method

// ONLINE-RUNNER:browser;

var text = '1234';
var substring = text.replace(/.{2}/, '');

console.log(substring); // 34
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Cross technology - remove first 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