Making a function that finds an id within a link

Hello everyone,
So I want to create a snippet that would be able to allow me to find an id within a url. So far I have created the following.

function myFunction() {
  var str = "https://www.example.com/id/1238992/post";
  var x = str.startsWith("1", 7);
  console.log("x")
}

the id will always be found in between /id/ and /posts and will always start with 1 and have a length of 7. This is why I have the “startsWith” as 1, and 7 for the length. But unfortunately I have had not avail in getting this snippet to work :disappointed:. Would anyone have any ideas that could possibly make this work? Thanks!

I would use the location API to obtain the path. Then we can use a regular expression to match against the first set of digits in the path.

var link = document.createElement("a");
link.href = "https://www.example.com/id/1238992/post";
var path = link.pathname;
var match = path.match(/(\d+)/);
var id = match[1];
console.log(id); // 1238992

oops I just realized that the URL is actually structured like this https://www.example.com/id/1238992?post
anyway to use the location API with a start of / and an end of ?

No problem, it all works the same.

so would I change match too

var match = path.math(/(\d+)?);

No, don’t change the code. The regular expression only cares about digits, nothing else.

The forward slashes are like quotation marks on strings. Regular expressions are contained inside the forward slashes. The forward slashes do not match against any of the text.

What about if there is letters in an id? Would I have to change the code?

Yes that’s right, but depending on the situation different things are done. We can cross that bridge when the new situation becomes a reality.

Or you could cross that bridge now, without resorting to regexes in the first place :stuck_out_tongue:

Since the ID will always be in the same location within the url, and URL’s are a structured format…

var str = "https://www.example.com/id/1238992/post";
var x = str.split("/")[4];

If you absolutely must use a regex, /id\/(\w*)\// will find any alphanum (roman alphabet), or /id\/(.*?)\// to find absolutely anything.

2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.