Keep only first n characters in a string?

前端 未结 7 1756
逝去的感伤
逝去的感伤 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: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

提交回复
热议问题