Sunday, 15 January 2012

jquery - JavaScript regExp returns "null" -



jquery - JavaScript regExp returns "null" -

i'm making regular look match li in 1 ul in 1 textarea. everytime click button, returns value of null.

here's fiddle.

here's function(){...} looks like:

function doit() { var input = document.getelementbyid("input"); var patt = /^<ol>{1}\n+\s?[<li>\w+<\/li>]+\n+<\/ol>{1}$/; alert(input.value.match(patt)); }

i don't know why patt doesn't work...

here's logic (in own words):

^ — starting point <ol>{1} — 1 <ol> \n+ — 1 or more new lines \s? — 0 or more (optional) spaces [<li>\w+<\/li>]+ — 1 or more <li></li> contains 1 or more characters. \n+ — 1 or more new lines <\/ol>{1} — 1 </ol> $ — ending point i want [<li>\w+<\/li>]+ homecoming 1 or more of like: <li>hello world :)</li>

basically, can in between <li></li>.

here pattern does:

^ — maches origin of string <ol — matches "<ol" >{1} — matches ">" 1 time \n+ — matches 1 or more new lines \s? — matches 1 whitespace character (optional) [<li>\w+<\/li>]+ — matches of characters in "<>a-za-z_/" 1 or more times \n+ — matches 1 or more new lines <\/ol — matches "</ol" >{1} — matches ">" 1 time $ — matches end of string

as match origin , end of string, pattern have match entire string, not part of string.

if set in textarea, pattern match it:

<ol> <li>helloworld</li><li>hellohowareyou</li><li>good</li> </ol>

you rather want this:

var patt = /<ol>\s*(?:<li>[\w !:)]+<\/li>\s*)+<\/ol>/;

explanation:

<ol> — matches "<ol>" \s* — matches 0 or more whitespace characters (including newlines) (?: — starts non-capturing grouping <li> — matches "<li>" [\w+ !:)]+ — matches of characters in "a-za-z_ !:)" 1 or more times <\/li> — matches "</li>" \s* — matches 0 or more whitespace characters ) — ends grouping + — repeats grouping 1 or more times \n+ — matches 1 or more new lines <\/ol> — matches "</ol>"

demo: http://jsfiddle.net/3jthn/2/

javascript jquery regex function methods

No comments:

Post a Comment