如何获取字符串的前三个字符

这可能与以前的主题重复,但我不能找到我真正需要的。

我想得到一个字符串的前三个字符,例如:

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

我想要这个字符串“012”的输出,但是我不想使用 subString 或类似的东西,因为我需要使用原始字符串来追加更多的字符“45”。使用子字符串它将输出01245,但我需要的是01212345。

154956 次浏览

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.

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: