Jump to content

Javascript Regular Expression


astralaaron

Recommended Posts

hello I am trying to pattern match against the window.location.I am having difficulty trying to figure out how to literally match a hyphen ( - ) within a hash name on a window.location//this doesn't work:if(/#calculated-by-yardage/.test(window.location)){}//this doesif(/#calculated/.test(window.location)){}the window location is something along the lines of:/index.html#calculated-by-yardageplease help !

Link to comment
Share on other sites

Use the backslash to escape reserved characters. And it's better to use window.location.href rather than window.location, because window.location is an object and not a string, even though it does returns a string when you call it

/#calculated\-by\-yardage/.test(window.location.href)

Link to comment
Share on other sites

I've checked this in FF, OP, and IE, and all of them print the same value, "true", for both document.write... Did I miss something?

<html>  <body>	 Hi! <br> <br>	 <script type="text/javascript">		var re1 = /#calculated-by-yardage/;		var re2 = /#calculated/;		var str = "/index.html#calculated-by-yardage";		document.write(re1.test(str) + "<br>");		document.write(re2.test(str) + "<br>");	 </script>  </body></html>

Link to comment
Share on other sites

I've checked this in FF, OP, and IE, and all of them print the same value, "true", for both document.write... Did I miss something?
<html>  <body>	 Hi! <br> <br>	 <script type="text/javascript">		var re1 = /#calculated-by-yardage/;		var re2 = /#calculated/;		var str = "/index.html#calculated-by-yardage";		document.write(re1.test(str) + "<br>");		document.write(re2.test(str) + "<br>");	 </script>  </body></html>

hey I just got here to see Ignols response (thanks by the way) I havent tried this. but in your example you forgot the back slashes on the dashes like he said, #calculated\-by\-yardage also i think you need to do the if(/pattern/.test(re1)) { do something } etc.. i might be wrong but im going to go try it now.
Link to comment
Share on other sites

Hyphens only have a special meaning in regular expressions when inside square brackets.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...