【问题标题】:SubString in JavaScript [duplicate]JavaScript中的子字符串[重复]
【发布时间】:2020-03-30 14:51:03
【问题描述】:

例如,我有一个如下字符串

var string = "test1;test2;test3;test4;test5";

我想要上面字符串中的以下子字符串,我不知道 startIndex,我唯一可以告诉子字符串应该从第二个分号开始到结尾。

var substring = "test3;test4;test5";

现在我想要像下面这样的子字符串

var substring2 = "test4;test5" 

如何在 JavaScript 中实现这一点

【问题讨论】:

  • const parts = string.split(';'), substring = parts.slice(2).join(';')
  • 您想要第三个分号之后的所有内容吗?还是您想要基于字符串中的实际静态位置的它?此外,您似乎已经为第二个分号工作了,同样的方法是否适用于第三个分号?
  • 位置不是静态的,有时在第二个分号之后,有时在第三个之后,有时在第四个之后,但每次都是随机的分号之后
  • @Rams 那么你给了这个随机数并且只想要 X 分号之后的字符串结尾吗?

标签: javascript substring indexof


【解决方案1】:

你是说这个吗?

const string = "test1;test2;test3;test4;test5";
const arr = string.split(";")
console.log(arr.slice(2).join(";")); // from item #2
console.log(arr.slice(-2).join(";")) // last 2 items

如果字符串很长,您可能需要使用这些版本之一 How to get the nth occurrence in a string?

作为一个函数

const string = "test1;test2;test3;test4;test5";
const restOfString = (string,pos) => { 
  const arr = string.split(";")
  return arr.slice(pos).join(";"); // from item #pos
};

console.log(restOfString(string,2))
console.log(restOfString(string,3))

【讨论】:

    【解决方案2】:

    尝试使用字符串splitjoin 的组合来实现此目的。

    var s = "test1;test2;test3;test4;test5";
    var a = s.split(";")
    console.log(a.slice(3).join(";"))

    【讨论】:

      猜你喜欢
      • 2010-09-17
      • 2014-11-05
      • 2022-01-07
      • 2020-12-19
      • 2016-02-12
      • 2013-01-11
      • 1970-01-01
      • 1970-01-01
      • 2011-07-25
      相关资源
      最近更新 更多