Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace a value at the end of a string converted to an array in one line?

Tags:

javascript

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";
like image 626
1.21 gigawatts Avatar asked Apr 06 '19 18:04

1.21 gigawatts


3 Answers

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);
like image 78
Nina Scholz Avatar answered Oct 18 '22 20:10

Nina Scholz


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`);
like image 4
Dan Kreiger Avatar answered Oct 18 '22 19:10

Dan Kreiger


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)
like image 2
adiga Avatar answered Oct 18 '22 20:10

adiga