Languages
[Edit]
EN

JavaScript - get first 3 characters of string

3 points
Created by:
Anisha-Kidd
652

In this short article, we would like to show you how to get the first 3 characters of a string in JavaScript.

Example 1

The below example shows the use of substring() method which returns the part of a string between the 0 and 3 indexes.

Runnable example:

// ONLINE-RUNNER:browser;

var text = '12345';
var substring = text.substring(0, 3);

console.log('text: ' + text); // 12345
console.log('substring: ' + substring); // 123

Output:

text: 12345
substring: 123

Example 2

In the second example, we can see the result when we want to get a substring from a string in various cases (like a string shorter than the number of characters we want to get or an empty string).

Runnable example:

// ONLINE-RUNNER:browser;

// true means string is empty

console.log(''.substring(0, 3) === ''); // empty
console.log('1'.substring(0, 3)); // 1
console.log('12'.substring(0, 3)); // 12
console.log('123'.substring(0, 3)); // 123
console.log('1234'.substring(0, 3)); // 123
console.log('12345'.substring(0, 3)); // 123

Output:

true
1
12
123
123
123

Note:
Don't use substr() because it's a non-standard method.

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 - get first 3 characters of 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