1

Edit: I think the issue is not with concatenation itself but the special character in the id of the element I am trying to select.

Original:

I am having problem with concatenating two strings. It seems the problem is because one of the strings contains '!'. Sadly, I have no control over what that string can contain. I tried using '+' to make single string of the two before I tried concat(). But the error remains the same.

The relevant code is $('#id_online_status_'.concat(msg.id)).removeClass('text-success').addClass('text-muted');

Error is this:

Uncaught Error: Syntax error, unrecognized expression: #id_online_status_specific.YqzvRnpU!OPMxkuoFQILY

Please help with fixing this. I am not much familiar with JS in general.

mplungjan
  • 169,008
  • 28
  • 173
  • 236
Newbie
  • 343
  • 2
  • 13
  • The concat is fine but you're trying to select an id with an `!` character which is illegal. Here's a [mcve] of your problem: `$("#!")`. – ggorlen Aug 14 '20 at 05:42
  • `const $status = $("[id='id_online_status_"+msg.id+'"]")` – mplungjan Aug 14 '20 at 05:52
  • or this: https://stackoverflow.com/questions/2786538/need-to-escape-a-special-character-in-a-jquery-selector-string – mplungjan Aug 14 '20 at 05:55
  • This should help you: $('#id_online_status_'.concat(msg.id.replace(/([!"#$%&'()*+,./:;<=>?@[\]^`{|}~])/g, '\\$1'))).removeClass('text-success').addClass('text-muted'); – hgb123 Aug 14 '20 at 05:58
  • You likely also can use this: `$("[id$='"+msg.id+"']")` – mplungjan Aug 14 '20 at 06:02

1 Answers1

0

change your code like this and try

$('#id_online_status_'+msg.id).removeClass('text-success').addClass('text-muted');

remove 'concat' and try with (+)