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.
Will this require me to use a regular expression, or is there a simpler way that I'm simply missing?
Thank you kindly in advance.
CodePudding user response:
No need to even convert to an array:
str.substring(str.indexOf(".") 1)
CodePudding user response:
You can use slice
method, and indexOf
to get the index
of the first dot.
let str = "service.annual.returns"
const result = str.slice(str.indexOf('.') 1)
console.log(result)
CodePudding user response:
You can use .split()
followed by .slice()
and then .join()
like so:
let str = "service.annual.returns";
let res = str.split('.').slice(1).join('.');
console.log(res);
First, using .split('.')
retruns an array like so:
['service', 'annual', 'returns']
The .slice(1)
then returns a new array containing all elements from index 1 onwards:
['annual', 'returns']
The .join('.')
then returns a string, which each of your elements within the array joined by a .
:
"annual.returns"
Otherwise, you can use .replace()
with a regular expression:
const str = "service.annual.returns";
const res = str.replace(/[^.]*\./, '');
console.log(res);
Here, the [^.]*\.
means match anything that is not a .
, followed by a .
, and replace that with an empty string.
CodePudding user response:
const newStr = str.split(".").filter(el => el != "service").join(".")
CodePudding user response:
str.split(".").slice(1).join(".")