1

hoping someone who knows a bit about javascript maybe able to help me. I need to extract part of the url of my pagepage to use in a javascript function and append to a url. ( it's for a power reviews setup.) the portion i need to extract is the number of the example below ie. www.mydomain.com/my-product-could-be-i950.html -- so would just need the 950 part.. the number part could be 2,3,4 characters. I then need to append this to the url www.mydomain.com/write-a-review.html?pr_page_id=950

could anyone help, it's a bit beyond me this one to be honest..

Many thanks.. Nathan

4 Answers 4

1
var num = location.pathname.match(/(\d+)\.html$/);

if( num ) {
    var url = 'www.mydomain.com/write-a-review.html?pr_page_id=' + num[1];
}
Sign up to request clarification or add additional context in comments.

2 Comments

You could replace the + after \d with {3,4} to have it must be 3 or 4 chars long.
True, but + is shorter and will work here since OP said that " the number part could be 2,3,4 characters". I don't think the point was to limit a potentially larger (or smaller) set of numbers.
0

Try this:

     <script type="text/javascript">
        function changeURL()
        {
            var szURL = location.pathname;
            szURL = "www.mydomain.com/my-product-could-be-i950.html";
            var num = szURL.replace(/\D/gi, "");
            szURL = "www.mydomain.com/write-a-review.html?pr_page_id=" + num;
            //Set URL
        }
     </script>

Comments

0

you could use regex:

var re = /i([0-9]{2,4})\.html$/;
var m = document.location.match(re);
if (m){
  document.location.href = 'http://www.mydomain.com/write-a-review.html?pr_page_id='+m[1];
}

Comments

0
 //current page URL    
cur = window.location

//regex to match your number
regex = /i[0-9]{2,4}\.html/;

//your number
num = cur.match(regex);

alert(num);

Not tested, Note that the variable num could be an array.

1 Comment

the dot should be escaped /i[0-9]{2,4}\.html/;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.