views:

42

answers:

1
<script type="text/javascript">
var str="Jestem bardzo, bardzo zadowolony. Można powiedzieć, że jestem również uszczęśliwiony i uspokojony."; 

patt1=new RegExp( "\bi\b", "g"); //<--- (to find the single word: "i")

document.write(str.match(patt1));
</script>

It works well as var pattern = /\bi\b/g; but not when using RegExp("\bi\b","g"). Why? (...thank you in advance)

+5  A: 

\ is the escape character in JavaScript strings. It's also the escape character in regular expressions! Since you're passing a string to the RegExp constructor, you have to escape the escape character...

patt1=new RegExp( "\\bi\\b", "g");
Shog9
Ahhh...! Thank you.
Sebastian
@Sebastian: please click on the big check-mark outline next to this answer to accept it.
Alan Moore