简体   繁体   English

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

[英]Keep only first n characters in a string?

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 个字符并删除 rest。

 const result = 'Hiya how are you'.substring(0,8); console.log(result); console.log(result.length);

You are looking for JavaScript's String method substring您正在寻找 JavaScript 的String方法substring

eg例如

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

Which returns the string starting at the first character and finishing before the 9th character - ie 'Hiya how'.它返回从第一个字符开始到第 9 个字符之前结束的字符串 - 即“Hiya how”。

substring documentation 子串文档

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也可以看看

Use substring function使用子串函数
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)

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

你可以试试:

myString.substring(0, 8);

Use the string.substring(from, to) API .使用string.substring(from, to) API In your case, use string.substring(0,8).在您的情况下,请使用string.substring(0,8).

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM