53
Help us understand the problem. What are the problem?

More than 5 years have passed since last update.

posted at

updated at

jQueryセレクタのエスケープ

jQueryの小ネタです。

セレクタに使用するときエスケープが必要な文字

公式の説明によれば、この31字

 !"#$%&'()*+,./:;<=>?@[\]^`{|}~

は2つのバックスラッシュ\\\でエスケープする必要があります。

Category: Selectors

To use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?@[]^`{|}~ ) as a literal part of a name, it must be escaped with with two backslashes: \.

エスケープするメソッドを作っておいて

function selectorEscape(val){
    return val.replace(/[ !"#$%&'()*+,.\/:;<=>?@\[\\\]^`{|}~]/g, '\\$&');
}

このようなときに

selectorを動的に組み立てたいようなときに使います。

function(form, val){
...
    var selector = 'input[name="' + name + '"][value="' + selectorEscape(val) +'"]';
    var found = form.find(selector);
...
}
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Sign upLogin
53
Help us understand the problem. What are the problem?