JavaScript chop/slice/trim off last character in string

我们两清 提交于 2019-11-26 03:24:59

问题


I have a string, 12345.00, and I would like it to return 12345.0.

I have looked at trim, but it looks like it is only trimming whitespace and slice which I don\'t see how this would work. Any suggestions?


回答1:


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



回答2:


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



回答3:


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



回答4:


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



回答5:


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



回答6:


Using JavaScript's slice function:

let string = 'foo_bar';
string = string.slice(0, -4); // Slice off last four characters here
console.log(string);

This could be used to remove '_bar' at end of a string, of any length.




回答7:


A regular expression is what you are looking for:

let str = "foo_bar";
console.log(str.replace(/_bar$/, ""));



回答8:


How about:

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



回答9:


Use regex:

let aStr = "12345.00";
aStr = aStr.replace(/.$/, '');
console.log(aStr);



回答10:


Try this:

const myString = "Hello World!";
console.log(myString.slice(0, -1));



回答11:


  1. (.*), captures any character multiple times

console.log("a string".match(/(.*).$/)[1]);
  1. ., matches last character, in this case

console.log("a string".match(/(.*).$/));
  1. $, matches the end of the string

console.log("a string".match(/(.*).{2}$/)[1]);



回答12:


Here is an alternative that i don't think i've seen in the other answers, just for fun.

var strArr = "hello i'm a string".split("");
strArr.pop();
document.write(strArr.join(""));

Not as legible or simple as slice or substring but does allow you to play with the string using some nice array methods, so worth knowing.




回答13:


const str = "test!";
console.log(str.slice(0, -1));



回答14:


debris = string.split("_") //explode string into array of strings indexed by "_"

debris.pop(); //pop last element off the array (which you didn't want)

result = debris.join("_"); //fuse the remainng items together like the sun



回答15:


If you want to do generic rounding of floats, instead of just trimming the last character:

var float1 = 12345.00,
    float2 = 12345.4567,
    float3 = 12345.982;

var MoreMath = {
    /**
     * Rounds a value to the specified number of decimals
     * @param float value The value to be rounded
     * @param int nrDecimals The number of decimals to round value to
     * @return float value rounded to nrDecimals decimals
     */
    round: function (value, nrDecimals) {
        var x = nrDecimals > 0 ? 10 * parseInt(nrDecimals, 10) : 1;
        return Math.round(value * x) / x;
    }
}

MoreMath.round(float1, 1) => 12345.0
MoreMath.round(float2, 1) => 12345.5
MoreMath.round(float3, 1) => 12346.0

EDIT: Seems like there exists a built in function for this, as Paolo points out. That solution is obviously much cleaner than mine. Use parseFloat followed by toFixed




回答16:


if(str.substring(str.length - 4) == "_bar")
{
    str = str.substring(0, str.length - 4);
}



回答17:


https://jsfiddle.net/invos/w3zeqv6v/

https://stackoverflow.com/questions/34817546/javascript-how-to-delete-last-two-characters-in-a-string

Just use trim if you don't want spaces

"11.01 °C".slice(0,-2).trim()




回答18:


The shortest way:

str.slice(0, -1); 



回答19:


In cases where you want to remove something that is close to the end of a string (in case of variable sized strings) you can combine slice() and substr().

I had a string with markup, dynamically built, with a list of anchor tags separated by comma. The string was something like:

var str = "<a>text 1,</a><a>text 2,</a><a>text 2.3,</a><a>text abc,</a>";

To remove the last comma I did the following:

str = str.slice(0, -5) + str.substr(-4);



回答20:


@Jason S:

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

Sorry for my graphomany but post was tagged 'jquery' earlier. So, you can't use slice() inside jQuery because slice() is jQuery method for operations with DOM elements, not substrings ... In other words answer @Jon Erickson suggest really perfect solution.

However, your method will works out of jQuery function, inside simple Javascript. Need to say due to last discussion in comments, that jQuery is very much more often renewable extension of JS than his own parent most known ECMAScript.

Here also exist two methods:

as our:

string.substring(from,to) as plus if 'to' index nulled returns the rest of string. so: string.substring(from) positive or negative ...

and some other - substr() - which provide range of substring and 'length' can be positive only: string.substr(start,length)

Also some maintainers suggest that last method string.substr(start,length) do not works or work with error for MSIE.




回答21:


Try this:

<script>
    var x="foo_foo_foo_bar";
    for (var i=0; i<=x.length; i++) {
        if (x[i]=="_" && x[i+1]=="b") {
            break;
        }
        else {
            document.write(x[i]);
        }
    }
</script>

You can also try the live working example on http://jsfiddle.net/informativejavascript/F7WTn/87/.




回答22:


Use substring to get everything to the left of _bar. But first you have to get the instr of _bar in the string:

str.substring(3, 7);

3 is that start and 7 is the length.



来源:https://stackoverflow.com/questions/952924/javascript-chop-slice-trim-off-last-character-in-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!