Trimming whitespace from the END of a string only, with jQuery

前端 未结 2 652
故里飘歌
故里飘歌 2021-02-07 05:28

I know of the jQuery $.trim() function, but what I need is a way to trim whitespace from the END of a string only, and NOT the beginning too.

So

  str =\         


        
相关标签:
2条回答
  • 2021-02-07 06:27

    You can use a regex:

    str = str.replace(/\s*$/,"");
    

    It says replace all whitespace at the end of the string with an empty string.

    Breakdown:

    • \s* : Any number of spaces
    • $ : The end of the string

    More on regular expressions:

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

    0 讨论(0)
  • 2021-02-07 06:34

    For some browsers you can use: str = str.trimRight(); or str = str.trimEnd();

    If you want total browser coverage, use regex.

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/trimEnd

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