You can use the substring function:
let str = "12345.00";
str = str.substring(0, str.length - 1);
console.log(str);
Run code snippetEdit code snippet Hide Results Copy to answer Expand
This is the accepted answer, but as per the conversations below, the slice syntax is much clearer:
let str = "12345.00";
str = str.slice(0, -1);
console.log(str);
Run code snippetEdit code snippet Hide Results Copy to answer Expand
Neither method mutates
Answer from Jon Erickson on Stack OverflowYou can use the substring function:
let str = "12345.00";
str = str.substring(0, str.length - 1);
console.log(str);
Run code snippetEdit code snippet Hide Results Copy to answer Expand
This is the accepted answer, but as per the conversations below, the slice syntax is much clearer:
let str = "12345.00";
str = str.slice(0, -1);
console.log(str);
Run code snippetEdit code snippet Hide Results Copy to answer Expand
Neither method mutates
You can use slice! You just have to make sure you know how to use it. Positive #s are relative to the beginning, negative numbers are relative to the end.
js>"12345.00".slice(0,-1)
12345.0
I am just making sure I am thinking about this correctly,
I have a .JSON file and it looks like this example
[{title: "title"}]And I need it to be {title: "title"}
So my idea is like, read the file then do some stuff then write a new file..
const fs = require('fs')
fs.readFile('./test.json', 'utf8' , (err, data) => {
if (err) {
console.error(err)
return
}
var result = data.substring(1, data.length-1);
})
fs.writeFile("finalOutput.json", JSON.stringify(result), function (err) {
if (err) return console.log(err);
return console.log("done");
});Something like this maybe wrapping the first one in a promise.
Does this make sense? Is there a better way?