Reputation: 485
How would I extract just the number from between the two slashes in this URL:
I only want the number (612 in this case but can be different no. and can vary in length) and nothing else.
The code I've attempted:
if(window.location.href.indexOf("id=") > -1){
var url = window.location.href;
console.log(url, 'url');
var findUrl = window.location.search;
console.log(findUrl, 'findUrl');
var url2 = url.substring(url.indexOf("=") + 1);
console.log(url2, 'url2');
var url3 = url.substring(
url.lastIndexOf("/") + 1,
url.lastIndexOf("/")
);
var url4 = url.split('/').pop().split('/')[0];
console.log(url3, 'url3');
console.log(url4, 'url4');
this.setState({
Id: url4,
filterValue: url4
}, () => {
this._editItemUrl();
});
}
I've read: How do you use a variable in a regular expression? JavaScript - Use variable in string match get string between two strings with javascript
Buy none answer my specific question.
Upvotes: 0
Views: 328
Reputation: 76
your problem is the forward slashes in the query-parameter string. If you can remove those (str replace) you can use JS's URLSearchParams.
see: https://www.sitepoint.com/get-url-parameters-with-javascript/
Upvotes: 1