JavaScript chop/slice/trim off last character in string

Mam łańcuch 12345.00 i chciałbym, aby zwrócił 12345.0.

Spojrzałem na trim, ale wygląda na to, że to tylko przycinanie białych znaków i slice, które nie widzę, jak to by działało. Jakieś sugestie?

Author: Peter Mortensen, 2009-06-05

22 answers

Możesz użyć funkcji substring :

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

Jest to akceptowana odpowiedź, ale zgodnie z poniższymi rozmowami składnia slice jest znacznie jaśniejsza:

var str = "12345.00";
str = str.slice(0, -1); // "12345.0"
 2566
Author: Jon Erickson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-12-28 00:29:58

Możesz użyć slice ! Musisz się tylko upewnić, że wiesz, jak go używać. Liczby dodatnie są względne do początku, liczby ujemne są względne do końca.

js>"12345.00".slice(0,-1)
12345.0
 1176
Author: Jason S,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-06 18:32:39

Możesz użyć metody substring obiektów JavaScript string:

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

Bezwarunkowo usuwa ostatnie cztery znaki z łańcucha s.

Jeśli jednak chcesz warunkowo usunąć ostatnie cztery znaki, tylko jeśli są one dokładnie _bar:

var re = /_bar$/;
s.replace(re, "");
 250
Author: Alex Martelli,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-15 19:10:03

Najprostszą metodą jest użycie metody slice łańcucha, która pozwala na pozycje ujemne (odpowiadające przesunięciom od końca łańcucha):

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

Jeśli potrzebujesz czegoś bardziej ogólnego, aby usunąć wszystko po ostatnim podkreśleniu, możesz wykonać następujące czynności (o ile s ma gwarancję, że będzie zawierać co najmniej jeden podkreślenie):

var s = "your_string";
var withoutLastChunk = s.slice(0, s.lastIndexOf("_"));
// withoutLastChunk == "your"
 152
Author: Tim Down,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-02-20 17:53:15

Dla liczby takiej jak twój przykład, polecam zrobić to przez substring:

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

Zauważ, że to faktycznie zaokrągli liczbę, chociaż, co wyobrażam sobie jest pożądane, ale może nie:

alert(parseFloat('12345.46').toFixed(1)); // 12345.5
 64
Author: Paolo Bergantino,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-06-04 20:52:33

Korzystanie z funkcji slice JavaScript:

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

To może być użyte do usunięcia '_bar' na końcu łańcucha o dowolnej długości.

 21
Author: Akshay Joshi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-01-30 07:50:57

Wyrażenie regularne jest tym, czego szukasz:

var str = "foo_bar";
alert(str.replace(/_bar$/, ""));
 14
Author: w35l3y,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-15 19:10:17

A może:

var myString = "12345.00";
myString.substring(0, myString.length - 1);
 9
Author: dariom,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-06-04 20:43:25
"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. (.* ), przechwytuje dowolny znak wielokrotnie
  2. ., dopasowuje ostatni znak, w tym przypadku
  3. $, dopasowuje koniec łańcucha
 7
Author: juanpastas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-12-28 04:46:22

Użyj regex:

var aStr = "12345.00";
aStr = aStr.replace(/.$/, '');
 7
Author: Marc477,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-07-29 04:58:25
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
 5
Author: uofc,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-05-27 10:47:10

Spróbuj tego:

var myString = "Hello World!";
myString.slice(0, -1);
 5
Author: Somwang Souksavatd,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-15 19:12:09

Oto alternatywa, której chyba nie widziałem w innych odpowiedziach, tylko dla Zabawy.

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

Nie jest tak czytelny i prosty jak slice lub substring, ale pozwala na zabawę z łańcuchem przy użyciu kilku ładnych metod tablicowych, więc warto wiedzieć.

 4
Author: Mark Walters,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-13 12:03:08

Jeśli chcesz zrobić ogólne zaokrąglenie pływaków, zamiast tylko przyciąć ostatni znak:

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: wydaje się, że istnieje wbudowana funkcja do tego celu, jak podkreśla Paolo. To rozwiązanie jest oczywiście dużo czystsze niż moje. Użyj parseFloat po którym następuje toFixed

 3
Author: PatrikAkerstrand,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-06-04 20:47:07
var str = "test!";
var newStr = str.slice(0,-1); //test
 3
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-11-20 15:52:29
if(str.substring(str.length - 4) == "_bar")
{
    str = str.substring(0, str.length - 4);
}
 1
Author: Matthew Flaschen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-08-30 03:08:50
 1
Author: invos,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:10:41

W przypadkach, gdy chcesz usunąć coś, co znajduje się blisko końca łańcucha (w przypadku łańcuchów o zmiennej wielkości), możesz połączyć slice() i substr ().

Miałem ciąg znaków ze znacznikami, dynamicznie zbudowany, z listą tagów anchor oddzielonych przecinkiem. Ciąg był coś w stylu:

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

Aby usunąć ostatni przecinek zrobiłem:

str = str.slice(0, -5) + str.substr(-4);
 -1
Author: bestafubana,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-15 19:16:38

Preferuję funkcję substring:

Var str = "12345.00";

Str = str.substring (0, str.długość-1);

Można również użyć funkcji Slice:

Var str = "12345.00";

Str = str.slice (-1); / / przekazanie wartości ujemnej jako pierwszego argumentu usuwa znaki z końca. Jest taki sam jak str.slice (0, -1)

Wynik dla obu metod to "12345.0".

 -1
Author: Animan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-19 07:53:53

@Jason S:

Możesz użyć slice! Po prostu musisz upewnij się, że wiesz, jak go używać. Dodatnie #S są względem początek, liczby ujemne to w stosunku do końca. 12345.00slice (0,-1) 12345.0

Sorry za mój grafomany ale post został wcześniej otagowany 'jquery'. Więc, nie możesz użyć slice () wewnątrz jQuery ponieważ slice () jest metodą jQuery do operacji z elementami DOM, a nie / align = "left" / .. Innymi słowy odpowiedz @Jon Erickson zaproponuj naprawdę idealne rozwiązanie.

Jednak twoja metoda będzie działać z funkcji jQuery, wewnątrz prostego Javascript. Muszę powiedzieć ze względu na ostatnią dyskusję w komentarzach, że jQuery jest znacznie częściej odnawialnym rozszerzeniem JS niż jego własny rodzic najbardziej znany ECMAScript.

Tutaj również istnieją dwie metody:

jako nasz:

string.substring(from,to) as plus if ' to ' index nulled Zwraca resztę string. więc: string.substring(from) pozytywny lub negatywny ...

i inne-substr () - które zapewniają zakres substr i 'długość' mogą być tylko dodatnie: string.substr(start,length)

Również niektórzy opiekunowie sugerują, że ostatnia metoda string.substr(start,length) nie działa lub działa z błędami dla MSIE.

 -3
Author: swift,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-06-16 22:38:12

Spróbuj tego:

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

Możesz również wypróbować przykład pracy na żywo na http://jsfiddle.net/informativejavascript/F7WTn/87/.

 -3
Author: kamal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-15 19:11:21

Użyj podłańcucha, aby uzyskać wszystko po lewej stronie _bar. Ale najpierw musisz uzyskać instr z _bar w łańcuchu:

str.substring(3, 7);

3 to początek, a 7 to długość.

 -6
Author: griegs,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-15 19:08:41