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

Как перевернуть строку в javascript

  • автор:

Перевернуть строку в JavaScript

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

Поскольку строки в JavaScript неизменяемы, на месте реверс строки невозможен. Есть несколько способов создать обратную копию строки с помощью JavaScript.

1. Использование Array.prototype.reverse() функция

Идея состоит в том, чтобы сначала преобразовать строку в массив символов, а затем вызвать Array.prototype.reverse() метод для реверсирования массива на месте. Наконец, соедините массив обратно в строку с помощью Array.prototype.join() метод.

Чтобы преобразовать строку в массив символов, вы можете использовать любой из следующих методов.

Reversing a String in JavaScript – Invert a string with the JS .reverse() Method

Joel Olawanle

Joel Olawanle

Reversing a String in JavaScript – Invert a string with the JS .reverse() Method

Reversing strings in JavaScript is something you’ll need to do often on your web development journey. You might need to reverse a string during interviews, when solving algorithms, or when doing data manipulation.

We will learn how to reverse a string in JavaScript using built-in JavaScript methods as well as the JavaScript reverse() method in this article.

For those in a rush, here is one line of code to help you reverse a string in JavaScript:

Or you can use this:

Let’s now discuss these methods and the role they play in helping us reverse strings in JavaScript.

How to Reverse a String With JavaScript Methods

Using JavaScript methods to reverse a string is simple. This is because we will use only three methods that perform different functions and are all used together to achieve this one common goal.

In general, we split the particular string into an array using either the spread operator or the split() method. Then we use the reverse() method, which can only be used to reverse elements in an array. And finally, we join this array together as a string using the join() method.

Let’s try each of these methods separately.

How to Split a String in JavaScript

There are two major methods of splitting a string in JavaScript: using the spread operator or the split() method.

How to Split String With the split() Method

The split() method is a very powerful method which you use to break a string into an ordered list of substrings based on a given pattern.

For example, if we have a sting of months separated by commas that we want to split up into an array of months, we could have something like this:

This will output the following array:

In our case our string might be a regular string with nothing separating each character. Then all we have to do is pass an empty string with no spaces, as seen below:

How to Split String with the Spread Operator

The spread operator is an ES6 addition that makes it easy to split up a string into an array. It does way more than just splitting a string:

How to Reverse an Array of Strings with the reverse() Method

So far, we’ve learned how to split a string. And the split() method, of course, divides the string into an array. And now you can apply the reverse array method to it, as shown below:

We can also apply this to the spread operator this way, but we will no loner be able to define how we want to split our string:

How to Join an Array of Strings Together with the join() Method

This is another powerful method that works in the opposite direction of the split() method. It creates a new string by concatenating all the elements in an array that are separated by commas or any other string specified as a separator.

For example, if we have an array of strings that we want to join into a single string separated by a dash (-), we can do something like this:

And this will return the following:

In our case, we have already reversed the string, and we don’t want anything in between. This means that we will just pass an empty string this way:

At the end, we can perform all these operations with just one line of code by bringing all the methods together in the proper order:

And the same applies to the spread operator:

Conclusion

In this tutorial, we learned how to reverse a string using the reverse() method, as well as other JavaScript methods. We also saw how the methods work with examples.

Three Ways to Reverse a String in JavaScript

Sonya Moisset

Reversing a string is one of the most frequently asked JavaScript question in the technical round of interview. Interviewers may ask you to write different ways to reverse a string, or they may ask you to reverse a string without using in-built methods, or they may even ask you to reverse a string using recursion.

There are potentially tens of different ways to do it, excluding the built-in reverse function, as JavaScript does not have one.

Below are my three most interesting ways to solve the problem of reversing a string in JavaScript.

Algorithm Challenge

Reverse the provided string.

You may need to turn the string into an array before you can reverse it.

Your result must be a string.

Как перевернуть строку в javascript

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

Итак, задача

Написать алгоритм на JavaScript, который перевернет строку «hello».

Решения

1. Обращаем строку с помощью встроенных функций в JS

В алгоритме мы будем использовать три метода: метод String.prototype.split(), метод Array.prototype.reverse() и метод Array.prototype.join().

  • Метод split() разбивает объект string на массив строк путём разделения строки указанной подстрокой.
  • Метод reverse() на месте обращает порядок следования элементов массива. Первый элемент массива становится последним, а последний — первым.
  • Метод join() объединяет все элементы массива в строку.

Шаг 1. Используем split() метод, чтобы вернуть новый массив.
Шаг 2. Используем reverse() метод, чтобы перевернуть созданный массив.
Шаг 3. Используем join() метод, чтобы соединить все элементы массива в строку.
Шаг 4. Возвращаем перевернутую строку.

Три метода вместе:

2. Переворачиваем строку с помощью цикла

Шаг 1. Создаем пустую строку, в которой будет размещаться новая строка.
Шаг 2. Создаем цикл FOR.
Шаг 3. Возвращаем перевернутую строку.

3. Переворачиваем строку с помощью рекурсии

Для этого решения мы будем использовать два метода: метод String.prototype.substr() и метод String.prototype.charAt().

Метод substr() возвращает указанное количество символов из строки, начиная с указанной позиции.

Метод charAt() возвращает указанный символ из строки.

Глубина рекурсии равна длине строки. Этот способ решения будет не самым удобным, если строка будет очень длинной.

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

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