user552769
user552769

Reputation: 101

Extract part of current url to use in javascript function

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

Upvotes: 1

Views: 454

Answers (4)

Pablo
Pablo

Reputation: 6058

 //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.

Upvotes: 0

Francesco Laurita
Francesco Laurita

Reputation: 23552

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];
}

Upvotes: 0

Chandu
Chandu

Reputation: 82913

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>

Upvotes: 0

user113716
user113716

Reputation: 322502

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

if( num ) {
    var url = 'www.mydomain.com/write-a-review.html?pr_page_id=' + num[1];
}

Upvotes: 1

Related Questions