Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
28
rated 0 times [  32] [ 4]  / answers: 1 / hits: 25392  / 11 Years ago, fri, october 25, 2013, 12:00:00

jQuery selector can't select an ID if it contains a . in it.

in my application ID name generates dynamically from usernames.



How can I escape any special character from tag IDs so that jQuery selector works well?



for example, ID1: This.Is.ID.1
ID2: This.is.Another.ID



Can anyone help me.



Thanks in advance.


More From » jquery

 Answers
22

If I understand you correctly, you want to modify a string that contains periods to have \ in front of every period, to be supported as an id in the jQuery selector. Here is how to do that:



var username = 'some.username.with.dots';

// Replace all periods with \. to
username = username.replace(/./g, '\\.');

// find element that matches #some\.username\.with\.dots
$('#' + username).doSomethingWithjQuery();



  • . means any character in regex, so you need to escape it by putting in front.

  • The g regex modifier means greedy, without it the replace expression would only replace the first . with \.



Edit
I tried my code, and it seems like you need to change the replace value to \\. to make it become \.



JS


[#74724] Thursday, October 24, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
efrainjamiry

Total Points: 234
Total Questions: 110
Total Answers: 112

Location: French Southern and Antarctic Lands
Member since Fri, Jan 6, 2023
1 Year ago
;