Javascript 只保留字符串中的前 n 个字符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7708819/
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-24 03:16:52  来源:igfitidea点击:

Keep only first n characters in a string?

javascript

提问by user978905

Is there a way in JavaScript to remove the end of a string?

JavaScript 中有没有办法删除字符串的结尾?

I need to only keep the first 8 characters of a string and remove the rest.

我只需要保留字符串的前 8 个字符并删除其余字符。

回答by Shad

You are looking for JavaScript's Stringmethod substring

您正在寻找 JavaScript 的String方法substring

e.g.

例如

'Hiya how are you'.substring(0,8);

Which returns the string starting at the first character and finishing before the 9th character - i.e. 'Hiya how'.

它返回从第一个字符开始到第 9 个字符之前结束的字符串 - 即“Hiya how”。

substring documentation

子串文档

回答by KooiInc

You could use String.slice:

你可以使用String.slice

var str = '12345678value';
var strshortened = str.slice(0,8);
alert(strshortened); //=> '12345678'

Using this, a String extension could be:

使用这个,字符串扩展可以是:

String.prototype.truncate = String.prototype.truncate ||
  function (n){
    return this.slice(0,n);
  };
var str = '12345678value';
alert(str.truncate(8)); //=> '12345678'

See also

也可以看看

回答by Wazy

Use substringfunction
Check this out http://jsfiddle.net/kuc5as83/

使用子字符串函数
检查这个http://jsfiddle.net/kuc5as83/

var string = "1234567890"
var substr=string.substr(-8);
document.write(substr);

Output >> 34567890

substr(-8)will keep last 8 chars

substr(-8)将保留最后 8 个字符

var substr=string.substr(8);
document.write(substr);

Output >> 90

substr(8)will keep last 2 chars

substr(8)将保留最后 2 个字符

var substr=string.substr(0, 8);
document.write(substr);

Output >> 12345678

substr(0, 8)will keep first 8 chars

substr(0, 8)将保留前 8 个字符

Check this out string.substr(start,length)

看看这个 string.substr(start,length)

回答by Mike Christensen

You could try:

你可以试试:

myString.substring(0, 8);

回答by Sahil Muthoo

var myString = "Hello, how are you?";
myString.slice(0,8);

回答by pimvdb

You can use .substring, which returns a potion of a string:

您可以使用.substring,它返回一个字符串药水:

"abcdefghijklmnopq".substring(0, 8) === "abcdefgh"; // portion from index 0 to 8

回答by Saket

Use the string.substring(from, to)API. In your case, use string.substring(0,8).

使用string.substring(from, to)API。在你的情况下,使用string.substring(0,8).