1

I have a url with format like this:

http://www.test.com/document/navigate/{{project_id}}/{{note_id}}

the value within {{}} will be filled with integer, like this for example

http://www.test.com/document/navigate/1/3
http://www.test.com/document/navigate/7/2
http://www.test.com/document/navigate/3

the value for note_id in the url is not mandatory, but i need to retrieve both for the project_id and note_id. how can i achieve that?

2 Answers 2

1

You can use a regular expression: http[s]?:\/\/www.test.com\/document\/navigate\/([\d]+)[\/]?([\d]+)?[\/]?.

Essentially it is laying out the protocol, hostname/domain, and the part of the path that we know. Then there are two capturing groups - the project ID and the note ID (optional).

You could use it like so:

const url = 'http://www.test.com/document/navigate/1/3';
const parts = url.match(/http[s]?:\/\/www.test.com\/document\/navigate\/([\d]+)[\/]?([\d]+)?/);

console.log(parts[0]); // "http://www.test.com/document/navigate/1/3"  <- full match
console.log(parts[1]); // "1"  <- first group
console.log(parts[2]); // "3"  <- second group, which will be undefined if left off

Note: this may not be a foolproof answer. I recommend trying out many other potential variations. Also be aware that this returns strings, so you may have to parseInt() or something if you want real numbers.

Here is a Regexr showing you how this works (this is how I mess around until I get it right).

Sign up to request clarification or add additional context in comments.

2 Comments

I'd simplify this by ignoring the scheme, domain, etc. and just look at window.location.pathname.
@TroyCarlson Good tip, though the OP did not say they were checking the current URL, so I couldn't assume. :)
0

One way you can make use of the part navigate/ like the following way:

var url1 = 'http://www.test.com/document/navigate/1/3';
var url2 = 'http://www.test.com/document/navigate/7/2';
var url3 = 'http://www.test.com/document/navigate/3';

function getValue(url){
  var arr = url.match(/navigate\/([^ ]*)/);
  arr = arr[arr.length - 1].split('/');
  if(arr.length == 1)
    return { project_id: +arr[0] };
  else if(arr.length == 2)
    return { project_id: +arr[0], note_id: +arr[1] };
  else
    return 'invalid';
}
console.log(getValue(url1));
console.log(getValue(url2));
console.log(getValue(url3));

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.