How do I chop/slice/trim off last character in string using Javascript?

ID : 341

viewed : 53

Tags : javascriptslicetrimjavascript

Top 5 Answer for How do I chop/slice/trim off last character in string using Javascript?

vote vote

94

You can use the substring function:

let str = "12345.00";  str = str.substring(0, str.length - 1);  console.log(str);

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);

vote vote

88

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 
vote vote

73

You can use the substring method of JavaScript string objects:

s = s.substring(0, s.length - 4) 

It unconditionally removes the last four characters from string s.

However, if you want to conditionally remove the last four characters, only if they are exactly _bar:

var re = /_bar$/; s.replace(re, ""); 
vote vote

64

The easiest method is to use the slice method of the string, which allows negative positions (corresponding to offsets from the end of the string):

const s = "your string"; const withoutLastFourChars = s.slice(0, -4); 

If you needed something more general to remove everything after (and including) the last underscore, you could do the following (so long as s is guaranteed to contain at least one underscore):

const s = "your_string";  const withoutLastChunk = s.slice(0, s.lastIndexOf("_"));  console.log(withoutLastChunk);

vote vote

56

For a number like your example, I would recommend doing this over substring:

console.log(parseFloat('12345.00').toFixed(1));

Do note that this will actually round the number, though, which I would imagine is desired but maybe not:

console.log(parseFloat('12345.46').toFixed(1));

Top 3 video Explaining How do I chop/slice/trim off last character in string using Javascript?

Related QUESTION?