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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39886730/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 23:01:39  来源:igfitidea点击:

Javascript How to get first three characters of a string

javascriptstring

提问by Phon Soyang

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.

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

回答by Alexander Nied

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.

现在您可以访问两者。

回答by Flimm

slice(begin, end)works on strings, as well as arrays. It returns a string representing the substring of the original string, from beginto end(endnot included) where beginand endrepresent the index of characters in that string.

slice(begin, end)适用于字符串和数组。它返回一个表示原始字符串的子字符串的字符串,从beginendend不包括)其中beginend表示该字符串中字符的索引。

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