-4

I have a URL string like so:

http://www.somedomain.com/code/12345/id/6789

I’d like to extract the text after “code” (1234) and “id” (6789) separately.

yqlim
  • 6,303
  • 3
  • 19
  • 39
catandmouse
  • 10,397
  • 22
  • 82
  • 139

4 Answers4

3

If you are sure your url is in this format only i.e. first key and then value. You can create a simple function like this:

function getParamFromUrl(url, key){
  const splitUrl = url.split('/')
  return splitUrl[splitUrl.indexOf(key) + 1]
}

const url = 'http://www.somedomain.com/code/12345/id/6789'
const valueOfCode = getParamFromUrl(url, 'code') // 12345
const valueOfId = getParamFromUrl(url, 'id') //6789

console.log('valueOfCode ' + valueOfCode)
console.log('valueOfId ' + valueOfId)
Ashish
  • 3,828
  • 15
  • 40
2

You could write a simple function by splitting url over / to get the value if the value always succeeds the text:

const url = 'http://www.somedomain.com/code/12345/id/6789';

function getValue(text) {
  const arr = url.split('/');
  return arr[arr.indexOf(text) + 1];
}

console.log(['code', 'id'].map(getValue));
shrys
  • 5,635
  • 2
  • 20
  • 32
1

const url = 'http://www.somedomain.com/code/12345/id/6789';
const splitString = url.split('/');
console.log('code',splitString[4]);
console.log('id',splitString[6]);
Santhosh S
  • 782
  • 5
  • 17
0

const url_string = "http://www.somedomain.com/code/12345/id/6789"; 
const url = new URL(url_string);
const tail = url_string.replace(url.origin,""); //→code/12345/id/6789";
const items= tail.split('/').filter(item => item.length > 0); //→["code", "12345", "id", "6789"]
console.log(items.filter(item => items.indexOf(item) % 2 === 1)); //→["12345", "6789"]
David
  • 15,335
  • 22
  • 54
  • 65