0

I want to extract the last part of this string : "https://steamcommunity.com/profiles/76561198364464404".Just the numbers after '/profiles'.But the problem is the URL can change sometimes.

There are two types of url

1.First one is "https://steamcommunity.com/profiles/76561198364464404" with "/profiles" and then the "id"(id is the numbers after '/profiles').

2."https://steamcommunity.com/id/purotexnuk".Second is this type.Where "/profiles" doesn't exist.

I have come up this code :

let inc;
const index = 27;
const string = 'https://steamcommunity.com/id/purotexnuk';
if (string.includes('profiles')) {
    inc = 9;
} else {
    inc = 3;
}

console.log(string.slice(index + inc, -1));

The above code checks wheather the string "/profiles" is present.If the string contains "/profiles".inc will be 9.So that slice starts from the right side of the string(url) and ends at the first '/' from the right.inc is 9 becuase "profiles/" length is 9.Similar way if the string(url) contains "id".The slice will start from the end and stop at the first '/' from the right.inc will be 3 becuase "id/" length is 3.

The index is always constant because ,"/profiles" or "/id" only occurs after "https://steamcommunity.com" whose length is 27.Is there any better way i can extract only the profile id or profile name?

(profile id - 76561198364464404)

(profile name - purotexnuk )

3 Answers 3

1

You can use regex for this, it will also take care if your url ends with / or has query parameters example https://steamcommunity.com/id/purotexnuk?ref=abc

/.*(?:profiles|id)\/([a-z0-9]+)[\/?]?/i

example:

const regex = /.*(?:profiles|id)\/([a-z0-9]+)[\/?]?/i;
const matches = regex.exec('https://steamcommunity.com/id/purotexnuk');
console.log(matches[1]);

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

1 Comment

This works whatever is in the URL.This is more dependable Thank you
1

You can split the string with delimiter / and return the last value value from the array;

function getNum(str) {
  const arr = str.split('/');
  if (!isNaN(arr[arr.length - 1])) {
    return arr[arr.length - 1];
  }
  return ' no number ';
}

const st1 = "https://steamcommunity.com/profiles/76561198364464404";
const st2 = "https://steamcommunity.com/profiles/76561198364464404";
const st3 = "https://steamcommunity.com/id/purotexnuk";

console.log(getNum(st1));
console.log(getNum(st2));
console.log(getNum(st3));

Comments

0

Or do it in one line:

const string = 'https://steamcommunity.com/id/purotexnuk';
console.log(string.slice(string.lastIndexOf("/") + 1, string.length));

2 Comments

this is better answer.
@Clutch Prince Yes this is the most optimal way,Because for any url the id or the profile name occurs after the last '/'.Perfect Thank you really appriciate your help.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.