escape dot in javascript

前端 未结 5 911
猫巷女王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

    0 讨论(0)
  • 2020-12-10 16:28

    The official jQuery FAQ has that exact question: How do I select an element by an ID that has characters used in CSS notation? They even have a function to help you escape. Quoting it:

    ... The colon (":") and period (".") are problematic within the context of a jQuery selector because they indicate a pseudo-class and class, respectively.

    In order to tell jQuery to treat these characters literally rather than as CSS notation, they must be "escaped" by placing two backslashes in front of them.

    // Does not work:
    $( "#some:id" )
     
    // Works!
    $( "#some\\:id" )
     
    // Does not work:
    $( "#some.id" )
     
    // Works!
    $( "#some\\.id" )
    

    The following function takes care of escaping these characters and places a "#" at the beginning of the ID string:

    function jq( myid ) {
        return "#" + myid.replace( /(:|\.|\[|\]|,|=)/g, "\\$1" );
    }
    

    The function can be used like so:

    $( jq( "some.id" ) )
    
    0 讨论(0)
  • 2020-12-10 16:29

    You don't actually need to remote the .'s from the id. You simply need to escape any special characters in the selector. For example, to select the following element:

    <div id='foo.bar'></div>
    

    ... you can use:

    $('#foo\\.bar');
    
    0 讨论(0)
  • 2020-12-10 16:32

    Use \\ (double backslash) to escape special characters.

    $('#this\\.something')
    

    Fiddle

    0 讨论(0)
  • 2020-12-10 16:32

    The the jQuery documentation states that two backslashes are used to escape them.

    So your example would use $("#This\\.Is\\.ID\\.1")

    0 讨论(0)
提交回复
热议问题