Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 604
Pars Avatar asked Oct 25 '13 18:10

Pars


People also ask

How do you escape a dot in JavaScript?

Let's say we want to find literally a dot. Not “any character”, but just a dot. To use a special character as a regular one, prepend it with a backslash: \. . That's also called “escaping a character”.

How do you escape dot?

(dot) metacharacter, and can match any single character (letter, digit, whitespace, everything). You may notice that this actually overrides the matching of the period character, so in order to specifically match a period, you need to escape the dot by using a slash \.

What is escape () in JS?

The escape() function in JavaScript is used for encoding a string. It is deprecated in JavaScript 1.5.

Do I need to escape dot in regex?

On regular-expressions.info, it is stated: Remember that the dot is not a metacharacter inside a character class, so we do not need to escape it with a backslash.


1 Answers

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

like image 181
Jesper Lindström Avatar answered Sep 17 '22 15:09

Jesper Lindström