Programing

jQuery 선택기 정규식

lottogame 2020. 10. 4. 10:17
반응형

jQuery 선택기 정규식


jQuery 선택기와 함께 와일드 카드 또는 정규식 (정확한 용어가 확실하지 않음) 사용에 대한 문서를 찾고 있습니다.

나는 이것을 직접 찾았지만 구문 및 사용 방법에 대한 정보를 찾을 수 없습니다. 구문에 대한 문서가 어디에 있는지 아는 사람이 있습니까?

편집 : 속성 필터를 사용하면 속성 값의 패턴을 기반으로 선택할 수 있습니다.


James Padolsey 는 정규식을 선택에 사용할 수 있는 멋진 필터만들었습니다 .

다음이 있다고 가정합니다 div.

<div class="asdf">

Padolsey의 :regex필터는 다음과 같이 선택할 수 있습니다.

$("div:regex(class, .*sd.*)")

또한 선택자에 대한 공식 문서를 확인하십시오 .


filter함수를 사용하여 더 복잡한 정규식 일치를 적용 할 수 있습니다 .

다음은 처음 세 div와 일치하는 예입니다.

$('div')
  .filter(function() {
    return this.id.match(/abc+d/);
  })
  .html("Matched!");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="abcd">Not matched</div>
<div id="abccd">Not matched</div>
<div id="abcccd">Not matched</div>
<div id="abd">Not matched</div>


도움이 될 수 있습니다.

포함으로 찾는 경우 다음과 같습니다.

    $("input[id*='DiscountType']").each(function (i, el) {
         //It'll be an array of elements
     });

Starts With에서 찾는다면 다음과 같을 것입니다.

    $("input[id^='DiscountType']").each(function (i, el) {
         //It'll be an array of elements
     });

Ends With찾는다면 다음과 같을 것입니다.

     $("input[id$='DiscountType']").each(function (i, el) {
         //It'll be an array of elements
     });

id가 주어진 문자열이 아닌 요소를 선택하려는 경우

    $("input[id!='DiscountType']").each(function (i, el) {
         //It'll be an array of elements
     });

이름에 공백으로 구분 된 지정된 단어가 포함 된 요소를 선택하려는 경우

     $("input[name~='DiscountType']").each(function (i, el) {
         //It'll be an array of elements
     });

id가 주어진 문자열과 같거나 해당 문자열로 시작하여 하이픈이 오는 요소를 선택하려는 경우

     $("input[id|='DiscountType']").each(function (i, el) {
         //It'll be an array of elements
     });

속성이 특정 문자열로 시작하는지 테스트하도록 정규식 사용이 제한되는 경우 ^ jquery 선택기를 사용할 수 있습니다.

For example if your want to only select div with id starting with "abc", you can use $("div[id^='abc']")

A lot of very useful selectors to avoid use of regex can be find here : http://api.jquery.com/category/selectors/attribute-selectors/


var test = $('#id').attr('value').match(/[^a-z0-9 ]+/);

Here you go!


Add a jQuery function,

(function($){
    $.fn.regex = function(pattern, fn, fn_a){
        var fn = fn || $.fn.text;
        return this.filter(function() {
            return pattern.test(fn.apply($(this), fn_a));
        });
    };
})(jQuery);

Then,

$('span').regex(/Sent/)

will select all span elements with text matches /Sent/.

$('span').regex(/tooltip.year/, $.fn.attr, ['class'])

will select all span elements with their classes match /tooltip.year/.


ids and classes are still attributes, so you can apply a regexp attribute filter to them if you select accordingly. Read more here: http://rosshawkins.net/archive/2011/10/14/jquery-wildcard-selectors-some-simple-examples.aspx


$("input[name='option[colour]'] :checked ")

If you just want to select elements that contain given string then you can use following selector:

$(':contains("search string")')


I'm just giving my real time example:

In native javascript I used following snippet to find the elements with ids starts with "select2-qownerName_select-result".

document.querySelectorAll("[id^='select2-qownerName_select-result']");

When we shifted from javascript to jQuery we've replaced above snippet with the following which involves less code changes without disturbing the logic.

$("[id^='select2-qownerName_select-result']")

참고URL : https://stackoverflow.com/questions/190253/jquery-selector-regular-expressions

반응형