Reputation: 2650
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);
$('div#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>
Upvotes: 0
Views: 856
Reputation: 1036
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 )
Upvotes: 1
Reputation: 25024
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());
Upvotes: 3
Reputation: 101614
Upvotes: 1
Reputation: 13342
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.
Upvotes: 5