Javascript How to get first three characters of a string

123,299

Solution 1

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

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:

Share:
123,299
Phon Soyang
Author by

Phon Soyang

Updated on July 05, 2022

Comments

  • Phon Soyang
    Phon Soyang almost 2 years

    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.