How to split a string and only return remaining values?

Viewed 58

I am working with a string that I would like to split and only return the remaining values.

The string looks as follows:

let str = "service.annual.returns"

I want to remove the "service" part of the string and only return "annual.returns".

I believe I can accomplish this with the .split() method, but not sure how the expression would look to get the desired result.

Apologies for being vague on the question. I indeed want to remove the first index, as the convention of the system I'm working on is to have a 'TYPE' appended to the name of a given element. For example, "Service" is just one such type, there are other instances such as "Tax": tax.annual.return, tax.zero.rated or another example is 'Media": media.youtube...this is important for the backend, but when showing the data to the frontend, I do not have to show the appended 'TYPE' formatting....that is only for the backend. I hope this makes it a bit clearer.

6 Answers

No need to even convert to an array:

str.substring(str.indexOf(".")+1)

You can use slice method, and indexOf to get the index of the first dot and skip by plus by one.

let str = "service.annual.returns"
const result = str.slice(str.indexOf('.') + 1)
console.log(result)

To remove the first "word"

str.split(".").slice(1).join(".")

And if you can have many "service" or not in the start of the string

str.split(".").filter(function(e){return e != "service";}).join(".")

A RegExp solution:

"service.annual.returns".match(/(?<=\.)([^.]+)/g)
// [ 'annual', 'returns' ]

Two different ways to achieve this :

// Input string
let str = "service.annual.returns";

// Find the first index of '.' by using `.indexOf` method and then get the sub string from the input string based on the index. 
console.log(str.substring(str.indexOf('.') + 1));

  • By splitting the str into an array based on the . and then remove the first element from an array and join back.

let str = "service.annual.returns";

console.log(str.split('.').slice(1).join('.'));

const newStr = str.split(".").filter(el => el != "service").join(".")
Related