JavaScript chop/slice/trim off last character in string

佐手、 提交于 2019-11-26 02:22:54
Jon Erickson

You can use the substring function:

var str = "12345.00";
str = str.substring(0, str.length - 1); // "12345.0"

This is the accepted answer, but as per the conversations below, the slice syntax is much clearer:

var str = "12345.00";
str = str.slice(0, -1); // "12345.0"

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
Alex Martelli

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

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

var s = "your string";
var 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):

var s = "your_string";
var withoutLastChunk = s.slice(0, s.lastIndexOf("_"));
// withoutLastChunk == "your"

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

alert(parseFloat('12345.00').toFixed(1)); // 12345.0

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

Using JavaScript's slice function:

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

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

w35l3y

A regular expression is what you are looking for:

var str = "foo_bar";
alert(str.replace(/_bar$/, ""));

How about:

var myString = "12345.00";
myString.substring(0, myString.length - 1);
"a string".match(/(.*).$/)[1] // => a strin

"a string".match(/(.*).$/) // returns ["a string", "a strin"]

"a string".match(/(.*).{2}$/)[1] // to get two chars off => a stri
  1. (.*), captures any character multiple times
  2. ., matches last character, in this case
  3. $, matches the end of the string

Use regex:

var aStr = "12345.00";
aStr = aStr.replace(/.$/, '');
Somwang Souksavatd

Try this:

var myString = "Hello World!";
myString.slice(0, -1);

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.

var str = "test!";
var newStr = str.slice(0,-1); //test
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

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

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

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

@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.

kamal

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/.

griegs

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.

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