Как удалить последний символ в строке js
Перейти к содержимому

Как удалить последний символ в строке js

  • автор:

JavaScript, как удалить последний символ в строке

Строки в JavaScript неизменяемы. Это значит, что после создания строку нельзя изменить. Когда нужно удалить последний символ из строки, то нужно создать новую строку без этого “лишнего” символа.

Удаляем последний символ в JS строке с помощью slice

Функция slice возвращает часть строки. Мы передаем в нее два аргумента, start и end . В результате slice вернет нам часть строки base между start и end .

Если end — отрицательное число, то поиск последнего элемента начнется с конца.

Значит то же, что и

Используем substring для удаления последнего символа JS строки

Так как функция slice возвращает нам подстроку и никак не меняет исходную строку, то мы вполне можем заменить ее на substring .

Обрати внимание, что если ты передашь вторым параметром в substring отрицательное число, то получишь в результате пустую строку

Поведение отличается от slice .

Выводы

Теперь ты знаешь как удалить последний символ строки в JS возможно тебе будет интересно узнать 4 способа сравнить строки в JavaScript

Удалить последний символ из строки в JavaScript

Бывают ситуации, когда нам нужно обрезать / вырезать / удалить символ из строки. Поскольку строка в JavaScript неизменяема, мы не можем изменить существующую строку, но мы должны создать новую строку с необходимыми изменениями. Мы можем удалить последний символ, используя различные методы, такие как регулярное выражение, получение подстроки, исключая последний символ, и т. Д. Мы увидим различные способы удаления последнего символа из строки JavaScript.

Используйте функцию substring() для удаления последнего символа из строки JavaScript

Мы используем метод substring() , чтобы вернуть часть строки между двумя индексами. Если указан только один индекс, он рассматривается как начальный индекс, и функция возвращает подстроку от начального индекса до последнего индекса строки. Чтобы удалить только последний символ из строки, мы должны предоставить конечный индекс как len — 1 , где len — это длина строки. Поскольку len-1 — это последний индекс строки, нам нужна строка перед символом в этом индексе.

Функция, похожая на substring() — substr() ; он также принимает два аргумента, но второй аргумент в случае substr() — это длина подстроки. Мы можем использовать его для достижения тех же результатов с помощью следующего кода.

Хотя он эквивалентен методу substring , его все же избегают, поскольку он считается устаревшим методом, и гораздо предпочтительнее использовать метод substring .

Используйте метод slice() , чтобы удалить последний символ из строки JavaScript

Метод slice() работает аналогично методу substring() . Он также принимает в качестве аргументов начальный индекс start_index и конечный индекс end_index . Существенная разница в том, что мы можем использовать отрицательные индексы в качестве аргументов функции. Отрицательный показатель доводят до нормального диапазона добавлением значения str.length . Мы можем отрезать последний символ, передав 0 в качестве начального индекса и -1 в качестве конечного индекса.

Используйте метод replace() для удаления последнего символа из строки JavaScript

Мы также можем удалить последний символ из строки с помощью функции replace() . Он принимает регулярное выражение в качестве входных данных и замену результатов регулярного выражения. Символ $ используется для обозначения конца ввода. Значок . используется для сопоставления одного символа. Таким образом, регулярное выражение /.$/ можно использовать для получения последнего символа из строки. После этого мы заменяем его на » , т.е. пустым, чтобы удалить его из строки.

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

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?

Liam's user avatar

25 Answers 25

You can use the substring function:

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

dota2pro's user avatar

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.

You can use the substring method of JavaScript string objects:

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 :

Peter Mortensen's user avatar

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

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

dota2pro's user avatar

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

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

dota2pro's user avatar

Paolo Bergantino's user avatar

Be aware that String.prototype. < split, slice, substr, substring >operate on UTF-16 encoded strings

None of the previous answers are Unicode-aware. Strings are encoded as UTF-16 in most modern JavaScript engines, but higher Unicode code points require surrogate pairs, so older, pre-existing string methods operate on UTF-16 code units, not Unicode code points. See: Do NOT use .split(») .

In addition, RegExp methods, as suggested in older answers, don’t match line breaks at the end:

Use the string iterator to iterate characters

Unicode-aware code utilizes the string’s iterator; see Array.from and . spread. string[Symbol.iterator] can be used (e.g. instead of string ) as well.

Use the s and u flags on a RegExp

The dotAll or s flag makes . match line break characters, the unicode or u flag enables certain Unicode-related features. Note that, when using the u flag, you eliminate unnecessary identity escapes, as these are invalid in a u regex, e.g. \[ is fine, as it would start a character class without the backslash, but \: isn’t, as it’s a : with or without the backslash, so you need to remove the backslash.

Note that some graphemes consist of more than one code point, e.g. ��️‍�� which consists of the sequence �� (U+1F3F3), VS16 (U+FE0F), ZWJ (U+200D), �� (U+1F308). Here, even Array.from will split this into four “characters”. Matching those is made easier with the RegExp set notation and properties of strings proposal.

Using JavaScript’s slice function:

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

dota2pro's user avatar

Akshay Joshi's user avatar

A regular expression is what you are looking for:

dota2pro's user avatar

dota2pro's user avatar

Performance

Today 2020.05.13 I perform tests of chosen solutions on Chrome v81.0, Safari v13.1 and Firefox v76.0 on MacOs High Sierra v10.13.6.

Conclusions

  • the slice(0,-1) (D) is fast or fastest solution for short and long strings and it is recommended as fast cross-browser solution
  • solutions based on substring (C) and substr (E) are fast
  • solutions based on regular expressions (A,B) are slow/medium fast
  • solutions B, F and G are slow for long strings
  • solution F is slowest for short strings, G is slowest for long strings

enter image description here

Details

I perform two tests for solutions A, B, C, D, E(ext), F, G(my)

  • for 8-char short string (from OP question) — you can run it HERE
  • for 1M long string — you can run it HERE

Solutions are presented in below snippet

Here are example results for Chrome for short string

enter image description here

Kamil Kiełczewski's user avatar

dota2pro's user avatar

dota2pro's user avatar

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

2. . , matches last character, in this case:

3. $ , matches the end of the string:

AlexSp3's user avatar

Just use trim if you don’t want spaces

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

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.

Mark Walters's user avatar

uofc's user avatar

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

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

Via slice(indexStart, indexEnd) method — note, this does NOT CHANGE the existing string, it creates a copy and changes the copy.

Via Regular Expression method — note, this does NOT CHANGE the existing string, it creates a copy and changes the copy.

Via array.splice() method -> this only works on arrays, and it CHANGES, the existing array (so careful with this one), you’ll need to convert a string to an array first, then back.

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:

To remove the last comma I did the following:

Peter Mortensen's user avatar

bestafubana's user avatar

You can, in fact, remove the last arr.length — 2 items of an array using arr.length = 2 , which if the array length was 5, would remove the last 3 items.

Sadly, this does not work for strings, but we can use split() to split the string, and then join() to join the string after we’ve made any modifications.

shreyasm-dev's user avatar

Try to use toFixed

Ali Yaghoubi's user avatar

Peter Mortensen's user avatar

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

Удалить последний символ из строки в JavaScript

В этом посте мы обсудим, как удалить последний символ из строки в JavaScript.

Невозможно на месте удалить символы из строки, поскольку строки неизменяемы в JavaScript. Идея состоит в том, чтобы вместо этого создать новую строку.

Есть несколько способов сделать это в JavaScript, используя substring() , slice() , или же substr() метод.

1. Использование substring() метод

The substring() Метод возвращает часть строки между указанными индексами. Вы можете использовать его следующим образом, чтобы удалить последний символ из строки:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *