Мастер-классы по Javascript Екатеринбург Ростов-на-Дону Москва Узнать больше...
Содержание (скрыть) Содержание (показать)

Opening HTML tag with attributes

Create a regexp to match opening HTML tags with attributes:

var re = /* your regexp */

var str = '<> <a href="/"> <input type="radio" checked> <b>'

alert(str.match(re)) // '<a href="/">', '<input type="radio" checked>', '<b>'

P.S. We know that there may not be < or > inside a tag (they are &lt; and &gt;).
P.P.S. <> is not a tag.

Решение
Решение

First, we start with <, then we could add .+?> to match any chars until >. So the regexp is <.+?>.

Let’s see how it works:

var re = /<.+?>/g

var str = '<> <a href="/"> <input type="radio" checked> **'

alert(str.match(re)) // '<> <a href="/">'

Wrong! It matches <> <a href="/">,* because .+? is *»any char (except newline) repeating one or more times until the rest of the pattern matches (lazyness)».

So, here’s what is does step by step:

  1. Match the first pattern symbol '<':
  2. Start matching .+ ungreedily. Match any symbol one time:
  3. Because the quantifier is lazy, try to match the rest of the pattern '>':

    No match.
  4. Repeat the quantifier and try to match the rest of the pattern again.


    No match.

  5. Repeat the quantifier until the match is found:
  6. We’ve got the result:

    Because the regexp is global, the new search starts right after the match.

So, the right solution is <[^>]+>. It won’t match <>, because needs at least non-'>' symbol:

var re = /<[^>]+>/g

var str = '<> <a href="/"> <input type="radio" checked> <b>'

alert(str.match(re)) // '<a href="/">', '<input type="radio" checked>', '<b>'

#281
Наверх

Реклама

Нашли опечатку?

Нашли опечатку на сайте? Что-то кажется странным?
Выделите соответствующий текст и нажмите Ctrl+Enter!

Последние Комментарии

Помоги другим!

Помоги другим узнать о хорошей статье!