Skip to content

[js] 第407天 手写一个trim()的方法 #2432

Open
@haizhilin2013

Description

@haizhilin2013
Collaborator

第407天 手写一个trim()的方法

作者:cxwht

3+1官网

我也要出题

Activity

wheatup

wheatup commented on May 27, 2020

@wheatup
'    ab  c   '.replace(/(^\s+)|(\s+$)/gm, '')  // "ab  c"
forever-z-133

forever-z-133 commented on May 28, 2020

@forever-z-133

你猜,和两个 for 相比哪个更快些。
按我理解的正则回溯的知识来看,这效率对比还真说不准。

bozaigao

bozaigao commented on Sep 22, 2020

@bozaigao

function trim(str) {
if (str[0] === ' ' && str[str.length - 1] === ' ') {
return trim(str.substring(1, str.length - 1))
} else if (str[0] !== ' ' && str[str.length - 1] === ' ') {
return trim(str.substring(0, str.length - 1))
} else if (str[0] === ' ' && str[str.length - 1] !== ' ') {
return trim(str.substring(1, str.length))
} else if (str[0] !== ' ' && str[str.length - 1] !== ' ') {
return str;
}
}

cool-delete

cool-delete commented on Sep 22, 2020

@cool-delete

function trim(str) {
if (str[0] === ' ' && str[str.length - 1] === ' ') {
return trim(str.substring(1, str.length - 1))
} else if (str[0] !== ' ' && str[str.length - 1] === ' ') {
return trim(str.substring(0, str.length - 1))
} else if (str[0] === ' ' && str[str.length - 1] !== ' ') {
return trim(str.substring(1, str.length))
} else if (str[0] !== ' ' && str[str.length - 1] !== ' ') {
return str;
}
}

@bozaigao
你可能想写尾递归 不过无论是浏览器环境 还是node默认配置 都不会启动尾递归优化哦

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    jsJavaScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @haizhilin2013@wheatup@bozaigao@cool-delete@forever-z-133

        Issue actions

          [js] 第407天 手写一个trim()的方法 · Issue #2432 · haizlin/fe-interview