【问题标题】:Replace all whitespace but except whitespace at the end替换所有空格,但最后的空格除外
【发布时间】:2017-08-07 09:03:39
【问题描述】:

我想替换所有空格,但不想替换字符串末尾的空格。 比如我的问题:

今天是悲伤的一天

今天是悲伤的一天-

str = "today is a sad day ";
newstr = str.replace(/\s/g,"-");

【问题讨论】:

  • 先使用修剪,删除空格。
  • 所以你想在字符串的末尾保留空格?
  • 你不是很清楚,你想保留尾随空格吗?请编辑您的问题以显示您的确切要求。
  • 您问题中的示例和文本不匹配。根据您的问题,结果应该是“今天是悲伤的一天”

标签: javascript regex


【解决方案1】:

trim();试试这个代码

str = "today is a sad day ";
str = str.trim();
newstr = str.replace(/\s/g,"-");
alert(newstr);

【讨论】:

    【解决方案2】:

    您需要使用trim() 去除字符串两边的空格:

    str = "today is a sad day ";
    console.log(str.trim().replace(/\s/g, "-"))

    【讨论】:

    • 只是一个警告,如果需要,String#trim() 在 IE8 中不可用。
    • do not want replace whitespace in the end of a string 所以我认为trim 正好相反
    【解决方案3】:

    只需将split(" ") 字符串与空格然后join('-') 一起使用

    注意 *:对于不需要的空间删除trim()函数

    console.log('today is a sad day '.trim().split(" ").join('-'))

    【讨论】:

    • OP示例在day之后有一个空格,如today is a sad day
    【解决方案4】:
    str = "today is a sad day ";
    newstr = str.replace(/\s(?!$)/g,"-");
    

    【讨论】:

    • 您最好解释一下您的解决方案,而不是简单地发布一些代码。也许值得一读How to write a good answer
    【解决方案5】:

    也许你想这样做?

    str = "today is a sad day ";
    toReplace = str.substring(0, str.length-1);
    newstr = toReplace.replace(/\s/g,"-");
    replaced = newstr + " ";
    console.log(replaced);

    【讨论】:

      【解决方案6】:

      使用String.prototype.replace(),您可以使用function (replacement) 创建新的子字符串,用于替换给定正则表达式的匹配项。提供给此函数的参数在“Specifying a function as a parameter”中进行了描述。

      您可以使用字符串的长度和当前的offset 来返回匹配项或所需的替换'-'

      代码:

      var str = 'today is a sad day ';
      var result = str.replace(/\s/g, function(match, offset, string) {
        return string.length - 1 !== offset ? '-' : match;
      });
      
      console.log(result);

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-11-20
        • 1970-01-01
        • 1970-01-01
        • 2017-09-24
        • 2018-04-15
        • 2012-12-16
        相关资源
        最近更新 更多