开发者

Regular expression in jQuery

I am a PHP coder and Javascript is new to me. Now I am reading some manuals about Regexp in Javascript. I can't do it work with jQuery.

Here are 2 examples.

http://jsfiddle.net/borayeris/utG6H/ This one is working:

<script type="text/javascript">
 $(function(){
     str = "For more information, see Chapter 3.4.5.1";
     re = /(chapter \d+(\.\d)*)/i;
     found = str.match(re);
    document.write(found);
 });
</script>

http://jsfiddle.net/borayeris/QyFPE/1/ This one not:

<script type="text/javascript">
 $(function(){
     str = "For more information, see Chapter 3.4.5.1";
     re = /(chapter \d+(\.\d)*)/i;
     found = str.match(re);
     $('开发者_如何学Godiv#write3').text(found);
 });
 </script>

The markup:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 
    Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>RegEx</title>
<script type="text/javascript" src="jquery-1.4.4.js"></script>
</head>
<body>

<div id="write3"></div>

</body>
</html>


Found is an array of matches (or null if nothing is found). Try changing this: $('div#write3').text(found); to this $('div#write3').text(found[0]);

See here for more information.


Drackir is correct, but misses the more interesting point in the difference between your working and not working examples. document.write expects a string, and the toString method of the array is called automatically. jQuery's text can take a string or a function, so the array's toString is not automatically called.

The truly parallel examples are:

document.write(found); 

and

$('div#write3').text(found.toString());


http://jsfiddle.net/QyFPE/5/

  1. You don't need to place the header, doctype, etc. in a jsfiddle, the blocks put the code in the appropriate place.
  2. This should work, the only change I made was placing the content in the correct location(s) (and un-grouped your pattern for catching sub-group numerics in your chapter number)


The dom function document.write will accept an array name as parameter and can print all the elements

eg: <script language="JavaScript">
<!--
var myarray = new Array();
for (i = 0; i < 10; i++)
{
    myarray[i] = i;
}
document.write(myarray);
//  -->
</script>

will give 0,1,2,3,4,5,6,7,8,9

Where as .text() function can only accept a string as parameter 
text( textString )
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜