ethyt
ethyt

Reputation: 123

discord.js how to slice a link

i am creating a steam command where the args are either the id or the profile link what i want to do is get the last word

ex https://steamcommunity.com/id/ethicalhackeryt/ here i want to get ethicalhackeryt or if user inputs that directly the continue

like .steam https://steamcommunity.com/id/ethicalhackeryt/ or .steam ethicalhackeryt

save args[0] as ethicalhackeryt

run: async (client, message, args) => {
        if(args[0] == `http://steamcommunity.com/id/`) args[0].slice(29); //needed help in this line
        const token = steamapi
        if(!args[0]) return message.channel.send("Please provide an account name!");
        const url ....... rest of code
    }

Upvotes: 0

Views: 389

Answers (2)

frobinsonj
frobinsonj

Reputation: 1167

You can use the following regex to pull out the data you need: /^(https:\/\/steamcommunity\.com\/id\/)?([^\s\/]+)\/?$/

Basically, this regex allows for the URL to be there (or not), followed by any characters that are not whitespace and not "/". Then at the end, it allows for a trailing "/".

I don't know what characters steam allows in their custom URLs. If you know, replace [^\s\/]+ with a regex that matches them.

This has the added benefit that it will reject values that do not match.

const tests = [
  'https://steamcommunity.com/id/ethicalhackeryt/',
  'https://steamcommunity.com/id/ethicalhackeryt',
  'ethicalhackeryt',
  'https://google.com/images'
]

tests.forEach(test => {
  
  const id = test.match(/^(https:\/\/steamcommunity\.com\/id\/)?([^\s\/]+)\/?$/);

  if (id) {
    console.log(test, id[2]);
  } else {
    console.log(test, 'Not a steam id');
  }
});

Upvotes: 1

Aaron
Aaron

Reputation: 1727

Not sure if I understood your problem correctly but this JS will get you always the ID no matter if you entered the link or just the name.

If this isnt what you wanted please specify your problem again.

Edit: wrapped everything inside a function to show each case easier.

console.log(getid("https://steamcommunity.com/id/ethicalhackeryt/"));
console.log(getid("ethicalhackeryt"));


function getid(id) {
  let split = id.split('/');
  split = split.filter(Boolean);
  return split[split.length - 1];
}

Upvotes: 0

Related Questions