Keep only first n characters in a string?

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

    Use substring function
    Check this out http://jsfiddle.net/kuc5as83/

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

    substr(-8) will keep last 8 chars

    var substr=string.substr(8);
    document.write(substr);
    
    Output >> 90
    

    substr(8) will keep last 2 chars

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

    substr(0, 8) will keep first 8 chars

    Check this out string.substr(start,length)

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