Remove line breaks from start and end of string

前端 未结 3 656
北恋
北恋 2021-02-03 17:02

I noticed that trim() does not remove new line characters from the start and end of a string, so I am trying to accomplish this with the following regex:

return          


        
相关标签:
3条回答
  • 2021-02-03 17:33

    String.trim() does in fact remove newlines (and all other whitespace). Maybe it didn't used to? It definitely does at the time of writing. From the linked documentation (emphasis added):

    The trim() method removes whitespace from both ends of a string. Whitespace in this context is all the whitespace characters (space, tab, no-break space, etc.) and all the line terminator characters (LF, CR, etc.).


    If you want to trim all newlines plus other potential whitespace, you can use the following:

    return str.trim();
    

    If you want to only trim newlines, you can use a solution that targets newlines specifically.

    0 讨论(0)
  • 2021-02-03 17:36

    /^\s+|\s+$/g should catch anything. Your current regex may have the problem that if your linebreaks contain \r characters they wouldn't be matched.

    0 讨论(0)
  • 2021-02-03 17:39

    Try this:

    str = str.replace(/^\s+|\s+$/g, '');
    

    jsFiddle here.

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