从字符串中提取某些子字符串

时间:2020-05-05 16:24:44

标签: javascript

我想提取此字符串的最后一部分:“ https://steamcommunity.com/profiles/76561198364464404”。只是'/ profiles'之后的数字。但是问题是URL有时会改变。

URL有两种类型

1。第一个是带有“ / profiles”的“ https://steamcommunity.com/profiles/76561198364464404”,然后是“ id”(id是“ / profiles”之后的数字)。

2。“ https://steamcommunity.com/id/purotexnuk”。第二种是这种类型。其中不存在“ / profiles”。

我想出了这段代码:

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));

上面的代码检查是否存在字符串“ / profiles”。如果该字符串包含“ /profiles”。inc将为9。因此该slice从字符串(url)的右侧开始并在第一个字符串结束右边的'/'是9,因为“ profiles /”的长度是9。如果字符串(url)包含“ id”,则以类似的方式。分片将从结尾处开始,并从右边的第一个'/'处停止.inc将为3,因为“ id /”长度为3。

索引总是恒定的,因为,“ / profiles”或“ / id”仅出现在长度为27的“ https://steamcommunity.com”之后。是否有更好的方法可以仅提取配置文件ID或配置文件名称?

(配置文件ID-76561198364464404)

(配置文件名称-purotexnuk)

3 个答案:

答案 0 :(得分:1)

您可以使用定界符/分割字符串,并从数组中返回最后一个值;

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));

答案 1 :(得分:1)

您可以为此使用正则表达式,如果您的网址以<template> <div class=""> <div> <b-card title="Card Title" body-class="text-center" header-tag="nav"> <template v-slot:header> <b-nav card-header tabs> <b-nav-item active>Active</b-nav-item> <b-nav-item>Inactive</b-nav-item> <b-nav-item disabled>Disabled</b-nav-item> </b-nav> </template> <b-card-text> With supporting text below as a natural lead-in to additional content. </b-card-text> <b-card-body> <b-sidebar visible="true" title="Sidebar" shadow> <div class="px-3 py-2"> <p> Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros. </p> <b-img src="https://picsum.photos/500/500/?image=54" fluid thumbnail ></b-img> </div> </b-sidebar> </b-card-body> <b-button variant="primary">Go somewhere</b-button> </b-card> </div> </div> </template> 结尾或具有查询参数示例/

,也要格外小心
https://steamcommunity.com/id/purotexnuk?ref=abc

示例:

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

答案 2 :(得分:0)

或者一行完成:

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