0

Currently I am scraping the end of an url using javascript like so:

var url = document.URL;
var sale = url.substring(url.lastIndexOf('/') + 1);
if(sale != "")

So if there is this /sales/1234 it would pick it up, trouble is it still works for something else like sales/anotherword/1234, is there an easy way to adjust this to only pick up the number after "/sales/"?

1

3 Answers 3

1

You could try using regular expressions:

var url = document.URL;
var sale = null;

var matches = url.match(/\/sales\/(\d+)/);

if(matches.length && matches[1]){
   sale = matches[1];
}
Sign up to request clarification or add additional context in comments.

Comments

0

You could do a bit more validating:

  1. Make sure there is no / after the one after sales.
  2. Make sure that the value you get is a number.

Something like this could work:

var url = document.URL;
var sale = url.substring(url.lastIndexOf('/sales/') + 1);
if(sale.indexOf('/') < 0 && !isNaN(sale)) {
    //Handle the sale
}
else {
    //sale either contains a / or is not a number
}

Comments

0

You could also do this :

var sale = parseInt(url.split('/sales/')[1], 10);
if (!isNaN(sale)) {
    // do something
}

parseInt() returns NaN (Not A Number) in case of failure.


Here is a function :

function toSaleId(url) {
    var id = parseInt(url.split('/sales/')[1], 10);
    if (!isNaN(id)) return id; 
}

Usage examples :

var sale = toSaleId('/sale/1234'); // 1234
var sale = toSaleId('/sale/1234/anotherworld'); // 1234
var sale = toSaleId('/sale/anotherworld/1234'); // undefined

Comments

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.