JavaScript 中的子字符串

SubString in JavaScript

例如,我有如下字符串

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

我想要上面字符串中的以下子字符串,我不知道 startIndex,我唯一能告诉的子字符串应该在第二个分号之后开始,直到结束。

var substring = "test3;test4;test5";

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

var substring2 = "test4;test5" 

如何在 JavaScript

中实现

你是这个意思?

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

尝试使用字符串 splitjoin 的组合来实现这一点。

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