• ARعربي
  • ENEnglish
  • ESEspañol
  • FAفارسی
  • FRFrançais
  • IDIndonesia
  • ITItaliano
  • JA日本語
  • KO한국어
  • RUРусский
  • TRTürkçe
  • UKУкраїнська
  • ZH简体中文

ما قصد داریم این پروژهٔ متن‌باز را در دسترس همهٔ مردم در سرتاسر دنیا قرار دهیم.

به ترجمهٔ محتوای این آموزش به زبان خودتان کمک کنید/a>.

    نقشه آموزش
    اشتراک گذاری
    • آموزش
    • عبارات باقاعده (Regular Expression)
    • Capturing groups
    بازگشت به درس
    این محتوا تنها در این زبان‌ها موجود است: English, Español, Français, Italiano, 日本語, Русский, Українська, 简体中文. لطفاً به ما

    Find color in the format #abc or #abcdef

    Write a RegExp that matches colors in the format #abc or #abcdef. That is: # followed by 3 or 6 hexadecimal digits.

    Usage example:

    let regexp = /your regexp/g;
    
    let str = "color: #3f3; background-color: #AA00ef; and: #abcd";
    
    alert( str.match(regexp) ); // #3f3 #AA00ef

    P.S. This should be exactly 3 or 6 hex digits. Values with 4 digits, such as #abcd, should not match.

    A regexp to search 3-digit color #abc: /#[a-f0-9]{3}/i.

    We can add exactly 3 more optional hex digits. We don’t need more or less. The color has either 3 or 6 digits.

    Let’s use the quantifier {1,2} for that: we’ll have /#([a-f0-9]{3}){1,2}/i.

    Here the pattern [a-f0-9]{3} is enclosed in parentheses to apply the quantifier {1,2}.

    In action:

    let regexp = /#([a-f0-9]{3}){1,2}/gi;
    
    let str = "color: #3f3; background-color: #AA00ef; and: #abcd";
    
    alert( str.match(regexp) ); // #3f3 #AA00ef #abc

    There’s a minor problem here: the pattern found #abc in #abcd. To prevent that we can add \b to the end:

    let regexp = /#([a-f0-9]{3}){1,2}\b/gi;
    
    let str = "color: #3f3; background-color: #AA00ef; and: #abcd";
    
    alert( str.match(regexp) ); // #3f3 #AA00ef
    • © 2007—2025  Ilya Kantor
    • دربارهٔ پروژه
    • تماس با ما