Codingjs re bs

 

Press Ctrl+Enter to quickly submit your post
Quick Reply  
 
 
  
 From:  CHYRON (DSMITHHFX)  
 To:  ALL
39501.1 
trying to extract the number from current page of a sequentially numbered bunch of web pages named "name-#.htm"
javascript code:
var thepage = /(\d+)/i.exec(window.location.href);

returns the page number twice, e.g. "71,71"

But I just want it once...

----
"Russian City Ever Watchful Against Being Sucked Into Earth"
0/0
 Reply   Quote More 

 From:  Matt  
 To:  CHYRON (DSMITHHFX)     
39501.2 In reply to 39501.1 
JavaScript Regex match / exec methods return an array of matches. To find the 1st parenthesized match, you would use thepage[1], e.g.:

JavaScript code:
var thepage = /(\d+)/i.exec(window.location.href);
alert(thepage[1]);


You might want to be more strict with your RegEx too. It is going to match any numbers in the URL, not just those that are in the pattern name-#.htm. For that you probably want to do something like this, assuming the number is always immediately before the .htm extension:

JavaScript code:
var thepage = /(\d+)\.htm/i.exec(window.location.href);

doohicky

0/0
 Reply   Quote More 

 From:  Peter (BOUGHTONP)  
 To:  CHYRON (DSMITHHFX)     
39501.3 In reply to 39501.1 
If you don't wrap your pattern in parentheses, you wont be unnecessarily capturing the content into group 1, and thus wont get two items in your array.

(You only need a capturing group when you need part of an expression, because the whole match is always captured.)

As Matt points out, just grabbing any sequence of numerical digital is possibly not specific enough.

However, I would probably do it this way instead:

javascript code:
var thepage = /\d+(?=\.htm)/i.exec(window.location.href);


And then you can either access thepage[0], or let it be converted to a string, and you'll have the number you want, only once.
0/0
 Reply   Quote More 

 From:  CHYRON (DSMITHHFX)  
 To:  Peter (BOUGHTONP)     
39501.4 In reply to 39501.3 

That works perfectly. Thanks!

 

Matt: fwiw (apparently not much), there are no other numbers in the url. That's probably the first javascript re I tried to write from scratch, as opposed to plagiarize + hack.


----
"Russian City Ever Watchful Against Being Sucked Into Earth"
0/0
 Reply   Quote More 

Reply to All    
 

1–4

Rate my interest:

Adjust text size : Smaller 10 Larger

Beehive Forum 1.5.2 |  FAQ |  Docs |  Support |  Donate! ©2002 - 2024 Project Beehive Forum

Forum Stats