String.prototype.trim = function () {
return /^\s*(.*?)\s*$/.exec(this)[1]
}
String.prototype.trim2 = function () {
return this.replace(/^\s*|\s*$/g, '')
}
String.prototype.trim3 = function () {
let len = this.length
let startIndex = -1
let endIndex = -1
let i = 0
while(startIndex === -1) {
if (this[i] !== ' ') {
startIndex = i
}
i++
}
i = this.length - 1
while(endIndex === -1) {
if (this[i] !== ' ') {
endIndex = i
}
i--
}
console.log(startIndex, endIndex)
return this.slice(startIndex, endIndex + 1)
}
let str = ' zhang '
console.log('--' + str.trim() + '--')
console.log('--' + str.trim2() + '--')
console.log('--' + str.trim3() + '--')
console