javascript tutorial - [Solved-5 Solutions] JavaScript chop/slice/trim off last character in string - javascript - java script - javascript array
Problem:
How to chop/slice/trim off last character in string?
Solution 1:
var str = "12345.00";
str = str.substring(0, str.length - 1);
click below button to copy the code. By JavaScript tutorial team
Solution 2:
We can use the substring method of JavaScript string objects:
s = s.substring(0, s.length - 4)
click below button to copy the code. By JavaScript tutorial team
unconditionally removes the last 4 characters from string s. However, if we want to conditionally remove the last 4 characters, only if they are exactly _bar:
var re = /_bar$/;
s.replace(re, "");
click below button to copy the code. By JavaScript tutorial team
Solution 3:
var s = "your_string";
var withoutLastChunk = s.slice(0, s.lastIndexOf("_"));
// withoutLastChunk == "your"
click below button to copy the code. By JavaScript tutorial team
Solution 4:
alert(parseFloat('12345.00').toFixed(1)); // 12345.0
click below button to copy the code. By JavaScript tutorial team
Do note that this will actually round the number, though, which I would imagine is desired but maybe not:
alert(parseFloat('12345.46').toFixed(1)); // 12345.5
click below button to copy the code. By JavaScript tutorial team
Solution 5:
var string='foo_bar';
string=string.slice(0,-4); //slice off last four characters here
click below button to copy the code. By JavaScript tutorial team
This could be use to remove '_bar' at end of string,with any length.