【问题标题】:Trimming whitespace from the END of a string only, with jQuery仅使用 jQuery 从字符串的 END 修剪空格
【发布时间】:2013-07-30 04:14:06
【问题描述】:

我知道 jQuery $.trim() 函数,但我需要的是一种只从字符串的 END 修剪空格的方法,而不是开头。

所以

  str ="     this is a string     ";

会变成

  str ="     this is a string";

有什么建议吗?

谢谢!

【问题讨论】:

    标签: javascript jquery trim


    【解决方案1】:

    您可以使用正则表达式:

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

    它说用空字符串替换字符串末尾的所有空格。

    细分:

    • \s* : 任意数量的空格
    • $ : 字符串结尾

    更多关于正则表达式:

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

    【讨论】:

    • 谢谢。节省了我的部分时间:)
    • 它也会删除新行
    【解决方案2】:

    对于某些浏览器,您可以使用: str = str.trimRight(); 或者 str = str.trimEnd();

    如果您想要全面覆盖浏览器,请使用正则表达式。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-16
      • 2010-10-20
      相关资源
      最近更新 更多