Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
704 views
in Technique[技术] by (71.8m points)

jquery - escape dot in javascript

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 Console


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...