Is there a way to replace the last item in array with one line of code?
What I receive:
return "my.long.string";
What I want:
return "my.long.output";
Code so far:
var value = "my.long.string";
var newValue = value.split(".").pop().join(".") + "output";
Error:
SyntaxError: Unexpected string
Update:
Nina answered it. I also had a case where I need to insert a value at the end of the string (add in a name to a file path). It's the same as above but replaces everything right before the last dot.
var value = "my.long.string";
var result = value.split(".").slice(0, -1).join(".") + "_stats." + "output";
You could slice the array and concat the last string. Array#slice
takes negative values for offsets from the end of the array.
var value = "my.long.string";
value = value.split('.').slice(0, -1).concat('output').join('.');
console.log(value);
You also don't have to convert it into an array. You could use lastIndexOf like so:
const value = "my.long.string";
console.log(`${value.substring(0,value.lastIndexOf('.'))}.output`);
You could use the regex (.*\.).*
to capture everything up until the final .
and replace
the last part with the new string (Regex demo). $1
gets the string from the capture group
let str = "my.long.string"
let newStr = str.replace(/(.*\.).*/, `$1output`);
console.log(newStr)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With