【问题标题】:Why the Ternary Operator isn't working right?为什么三元运算符不能正常工作?
【发布时间】:2015-10-07 18:03:59
【问题描述】:

嗯,我在聊天室网站工作...我遇到了这个问题...出于某种原因,三元运算符没有给我正确的输出...

这是完成工作的代码片段......

html = html.replace(/(@[a-zA-Z0-9]{1,})/, "<span class='" + (myUsername == "$1".replace('@', '') ? "highlighted-username" : "") + "'>$1</span>");

假设我的名字是“jimisdam”,有人在聊天中写道“@jimisdam”......所以......我得到了 1 美元并删除了 '@' 以将其与 myUsername(即"jimisdam")

怎么了??

【问题讨论】:

标签: javascript html replace ternary-operator


【解决方案1】:

JS 不知道您希望它在替换之前将 $1 替换到位。它看到一个对 html.replace 的方法调用,它需要 2 个参数:

  • 要匹配的正则表达式
  • 要替换的字符串

为了计算第二个参数,它计算这个表达式:

"<span class='" + (myUsername == "$1".replace('@', '') ? "highlighted-username" : "") + "'>$1</span>"

请注意,$1 在这里没有任何特殊意义,因为我们仍在决定将什么字符串传递给替换函数。所以:

  • "$1".replace('@', '') 只会导致 "$1"
  • 所以除非您的用户名恰好是 $1,否则比较将始终为假
  • 所以会在类属性中添加一个空字符串
  • 所以传递的参数总是"&lt;span class=''&gt;$1&lt;/span&gt;"

直到现在replace 才能看到 $1 的剩余实例并替换为捕获的值。

实现您想要做的事情的一种方法是pass in a function rather than a string as the second parameter。这样,您将字符串的匹配部分作为变量获取,并可以使用它们来计算替换。

未经测试的示例,因为我在打电话:

html = html.replace(/(@[a-zA-Z0-9]{1,})/, function(match) { return "<span class='" + (myUsername == match.replace('@', '') ? "highlighted-username" : "") + "'>" + match + "</span>"; })

【讨论】:

    【解决方案2】:

    您的“$1”字符串文字不包含子匹配项。错了。

    但是,replace() 方法也将函数作为第二个参数。试试这个:

    html = html.replace(/(@[a-zA-Z0-9]{1,})/,function(){
        return '<span class="' +
               (myUsername == arguments[0].replace('@','') ? 'highlighted-username' : '')
               + '">' + arguments[0] + '</span>';
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-25
      • 1970-01-01
      • 2021-02-06
      • 2013-07-30
      • 1970-01-01
      • 2021-09-02
      • 2013-04-11
      • 1970-01-01
      相关资源
      最近更新 更多