escape dot in javascript

前端 未结 5 916
猫巷女王i
猫巷女王i 2020-12-10 15:49

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 esca

5条回答
  •  臣服心动
    2020-12-10 16:23

    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

提交回复
热议问题