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