在JavaScript中转义点 [英] escape dot in javascript
本文介绍了在JavaScript中转义点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
jQuery选择器如果包含。
,则无法选择ID。
我的应用程序ID名称中的
是从用户名动态生成的。
jQuery selector can't select an ID if it contains a .
in it.
in my application ID name generates dynamically from usernames.
如何从标记ID 中转义任何特殊字符,以便jQuery选择器正常工作?
How can I escape any special character from tag IDs so that jQuery selector works well?
例如,ID1: This.Is.ID.1
ID2: This.is.Another.ID
任何人都可以帮助我。
提前致谢。
推荐答案
如果我理解正确,你想修改一个包含句点的字符串,在每个句点前面都有\\,作为一个支持jQuery选择器中的id。以下是如何做到这一点:
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();
-
。
在正则表达式中表示任何字符,因此您需要通过在前面放置\
来逃避它。 -
g
正则表达式修饰符意味着贪婪,没有它,替换表达式只会替换第一个。
与\\ 。
.
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\\.
编辑
我尝试了我的代码,它您似乎需要将替换值更改为 \\\\。
,使其成为 \\。
这篇关于在JavaScript中转义点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文