0

For example, I have a string like following

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

I want the following substring from the above string, I don't know the startIndex, the only thing I can tell substring should start after the second semicolon to till the end.

var substring = "test3;test4;test5";

Now I want to have substring like following

var substring2 = "test4;test5" 

How to achieve this in JavaScript

Rams
  • 2,141
  • 5
  • 33
  • 59
  • This is the answer: https://stackoverflow.com/questions/14480345/how-to-get-the-nth-occurrence-in-a-string – Alex Brohshtut Mar 30 '20 at 14:53
  • 2
    `const parts = string.split(';'), substring = parts.slice(2).join(';')` – Yevhen Horbunkov Mar 30 '20 at 14:54
  • Are you wanting everything after the third semi-colon in general? Or do you want an it based on an actual static position in the string? Also it seems like you have something already working for the second semicolon, wouldn't that same approach be applicable for the third? – Spencer Wieczorek Mar 30 '20 at 14:56
  • the position is not static, sometimes it is after second semicolon, sometimes it is after 3rd and sometimes after 4th , but every time it is after the some random semicolon only – Rams Mar 30 '20 at 15:00
  • @Rams So are you given this random number and just want the end of the string after X semicolons? – Spencer Wieczorek Mar 30 '20 at 15:03
  • @SpencerWieczorek yes exactly – Rams Mar 30 '20 at 15:04
  • @Rams In that case both the answers below should be sufficient to what you want. Just enter the number you want rather than the static number used or use the function in mplungjan answer. Although this type of question was asked before, see the first link. – Spencer Wieczorek Mar 30 '20 at 15:09

2 Answers2

3

You mean this?

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

If the string is very long, you may want to use one of these versions How to get the nth occurrence in a string?

As a function

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))
mplungjan
  • 169,008
  • 28
  • 173
  • 236
1

Try to use a combination of string split and join to achieve this.

var s = "test1;test2;test3;test4;test5";
var a = s.split(";")
console.log(a.slice(3).join(";"))
Jayram
  • 18,820
  • 6
  • 51
  • 68