Escape dot in javascript

The jQuery selector cannot select an identifier if it contains .it.
in my application id name is dynamically generated from usernames.

How can I avoid any special character from tag tags so that the jQuery selector works well?

e.g. ID1: This.Is.ID.1 ID2:This.is.Another.ID

Can anybody help me.

Thanks in advance.

+4
source share
5 answers

If you understand correctly, you want to change the line containing the periods to have \\ before each period, to support as an identifier in the jQuery selector. Here's how to do it:

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();
  • . " " , , \ .
  • regex g , replace . \\.

Edit , , \\\\., \\.

Js console

+12

jQuery FAQ : , , CSS? , . :

... ( ":" ) ( "." ) jQuery, .

jQuery , CSS, "", .

// Does not work:
$( "#some:id" )

// Works!
$( "#some\\:id" )

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

// Works!
$( "#some\\.id" )

"#" ID:

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

:

$( jq( "some.id" ) )
+7

\\ ( ) .

$('#this\\.something')

Fiddle

+1

You really don't need to delete. from identifier. You just need to avoid any special characters in the selector. For example, to select the following item:

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

... you can use:

$('#foo\\.bar');
0
source

The jQuery documentation claims that two backslashes are used to eliminate them.

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

0
source

All Articles