Javascript How to get first three characters of a string

JavascriptString

Javascript Problem Overview


This may duplicate with previous topics but I can't find what I really need.

I want to get a first three characters of a string. For example:

var str = '012123';
console.info(str.substring(0,3));  //012

I want the output of this string '012' but I don't want to use subString or something similar to it because I need to use the original string for appending more characters '45'. With substring it will output 01245 but what I need is 01212345.

Javascript Solutions


Solution 1 - Javascript

var str = '012123';
var strFirstThree = str.substring(0,3);

console.log(str); //shows '012123'
console.log(strFirstThree); // shows '012'

Now you have access to both.

Solution 2 - Javascript

slice(begin, end) works on strings, as well as arrays. It returns a string representing the substring of the original string, from begin to end (end not included) where begin and end represent the index of characters in that string.

const string = "0123456789";
console.log(string.slice(0, 2)); // "01"
console.log(string.slice(0, 8)); // "01234567"
console.log(string.slice(3, 7)); // "3456"

See also:

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPhon SoyangView Question on Stackoverflow
Solution 1 - JavascriptAlexander NiedView Answer on Stackoverflow
Solution 2 - JavascriptFlimmView Answer on Stackoverflow