113

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.

5
  • 5
    In this case, when it's a string, you'd be getting the characters, not necessarily digits. But I'm confused - you are getting the first 3 characters of the string. So what are you trying to do?
    – elzi
    Commented Oct 6, 2016 at 2:52
  • Strings are immutable.
    – PM 77-1
    Commented Oct 6, 2016 at 2:52
  • 4
    substring will return a new string 012, but str will still be equal to 012123. substring will not change the contents of str. Commented Oct 6, 2016 at 2:52
  • 2
    Please edit your question to show how you are trying to use the results. Calling .substring() (or .slice() or .substr()) doesn't change the original string at all, it returns a new string. str doesn't change unless you explicitly overwrite it with str = str.substring(0,3).
    – nnnnnn
    Commented Oct 6, 2016 at 2:52
  • 2
    The above commenters are correct-- the method just returns what you want without changing the original string. So you can store the returned value in a variable like strFirstThree = str.substring(0,3) and still have access to str in its entirety. Commented Oct 6, 2016 at 2:54

2 Answers 2

184

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.

30

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:

1
  • 1
    And if you omit the end then it will give you back the rest of the string from the start. With string from above: console.log(string.slice(7)); // "789"
    – wkille
    Commented Jan 21, 2023 at 18:54

Not the answer you're looking for? Browse other questions tagged or ask your own question.