Keep only first n characters in a string?

前端 未结 7 1648
逝去的感伤
逝去的感伤 2020-11-29 16:37

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

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

相关标签:
7条回答
  • 2020-11-29 17:20

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

    0 讨论(0)
  • 2020-11-29 17:23

    You could use 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

    0 讨论(0)
  • 2020-11-29 17:23

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

    "abcdefghijklmnopq".substring(0, 8) === "abcdefgh"; // portion from index 0 to 8
    
    0 讨论(0)
  • 2020-11-29 17:28
    var myString = "Hello, how are you?";
    myString.slice(0,8);
    
    0 讨论(0)
  • 2020-11-29 17:31

    You could try:

    myString.substring(0, 8);
    
    0 讨论(0)
  • 2020-11-29 17:32

    You are looking for JavaScript's String method 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'.

    substring documentation

    0 讨论(0)
提交回复
热议问题