javascript - Why the Ternary Operator isn't working right? -


well, i'm working in chat room website... , have problem... reason ternary operator doesn't give me right output...

that's code piece of code job...

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

let's name "jimisdam" , writes in chat "@jimisdam"... so... i'm getting $1 , removing '@' compare myusername(which "jimisdam")

what's wrong ??

js doesn't know want substitute $1 place before doing replacement. sees method call html.replace takes 2 arguments:

  • the regex match
  • the string replace with

to calculate second parameter, evaluates expression:

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

note $1 doesn't mean special here, because we're still deciding string pass replacement function. so:

  • "$1".replace('@', '') results in "$1"
  • so unless username happens $1, comparison false
  • so empty string added class attribute
  • so argument passed "<span class=''>$1</span>"

only replace see remaining instance of $1 , substitute in captured value.

one way achieve you're trying pass in function rather string second parameter. way, matched sections of string variables, , can use them calculate replacement.

untested example, because i'm on phone:

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

Comments

Popular posts from this blog

qt - Using float or double for own QML classes -

Create Outlook appointment via C# .Net -

ios - Swift Array Resetting Itself -