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

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

  • автор:

Как преобразовать строку в массив js?

Аватар пользователя Ivan Gagarinov

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

В примере выше использовался метод split для разделения строк на элементы по определенному разделителю. Если указать в качестве разделителя пустую строку, то на выходе получим массив из символов:

Также строки имеют некоторые свойства массивов: их можно перебирать в циклах а также можно обращаться к символам через индексы:

Есть также быстрый способ разбить строку на символы с использованием рест-оператора:

Аватар пользователя Виктория Аблаева

Помимо вышеупомянутых способов преобразования строки в массив, есть ещё один метод, которым можно воспользоваться.
Это Array.from():
Данный метод работает очень просто. Вся его работа описана в примере ниже:

У данного метода есть особенность, которая может показаться недостатком.
Если в строке между словами, буквами или цифрами будут знаки препинания либо пробелы, они также станут элементами массива.

String.prototype.split()

The split() method takes a pattern and divides a String into an ordered list of substrings by searching for the pattern, puts these substrings into an array, and returns the array.

Try it

Syntax

Parameters

The pattern describing where each split should occur. Can be undefined , a string, or an object with a Symbol.split method — the typical example being a regular expression. Omitting separator or passing undefined causes split() to return an array with the calling string as a single element. All values that are not undefined or objects with a @@split method are coerced to strings.

A non-negative integer specifying a limit on the number of substrings to be included in the array. If provided, splits the string at each occurrence of the specified separator , but stops when limit entries have been placed in the array. Any leftover text is not included in the array at all.

  • The array may contain fewer entries than limit if the end of the string is reached before the limit is reached.
  • If limit is 0 , [] is returned.

Return value

An Array of strings, split at each point where the separator occurs in the given string.

Description

If separator is a non-empty string, the target string is split by all matches of the separator without including separator in the results. For example, a string containing tab separated values (TSV) could be parsed by passing a tab character as the separator, like myString.split(«\t») . If separator contains multiple characters, that entire character sequence must be found in order to split. If separator appears at the beginning (or end) of the string, it still has the effect of splitting, resulting in an empty (i.e. zero length) string appearing at the first (or last) position of the returned array. If separator does not occur in str , the returned array contains one element consisting of the entire string.

If separator is an empty string ( «» ), str is converted to an array of each of its UTF-16 «characters», without empty strings on either ends of the resulting string.

Note: «».split(«») is therefore the only way to produce an empty array when a string is passed as separator .

Warning: When the empty string ( «» ) is used as a separator, the string is not split by user-perceived characters (grapheme clusters) or unicode characters (code points), but by UTF-16 code units. This destroys surrogate pairs. See «How do you get a string to a character array in JavaScript?» on StackOverflow.

If separator is a regexp that matches empty strings, whether the match is split by UTF-16 code units or Unicode code points depends on if the u flag is set.

If separator is a regular expression with capturing groups, then each time separator matches, the captured groups (including any undefined results) are spliced into the output array. This behavior is specified by the regexp’s Symbol.split method.

If separator is an object with a Symbol.split method, that method is called with the target string and limit as arguments, and this set to the object. Its return value becomes the return value of split .

Any other value will be coerced to a string before being used as separator.

Examples

Using split()

When the string is empty and a non-empty separator is specified, split() returns [«»] . If the string and separator are both empty strings, an empty array is returned.

The following example defines a function that splits a string into an array of strings using separator . After splitting the string, the function logs messages indicating the original string (before the split), the separator used, the number of elements in the array, and the individual array elements.

This example produces the following output:

Removing spaces from a string

In the following example, split() looks for zero or more spaces, followed by a semicolon, followed by zero or more spaces—and, when found, removes the spaces and the semicolon from the string. nameList is the array returned as a result of split() .

This logs two lines; the first line logs the original string, and the second line logs the resulting array.

Returning a limited number of splits

In the following example, split() looks for spaces in a string and returns the first 3 splits that it finds.

Splitting with a RegExp to include parts of the separator in the result

If separator is a regular expression that contains capturing parentheses ( ) , matched results are included in the array.

Note: \d matches the character class for digits between 0 and 9.

Using a custom splitter

An object with a Symbol.split method can be used as a splitter with custom behavior.

The following example splits a string using an internal state consisting of an incrementing number:

The following example uses an internal state to enforce certain behavior, and to ensure a «valid» result is produced.

Преобразование строки в массив в JavaScript

Преобразование строки в массив в JavaScript

Мы представим три метода преобразования строки в массив в JavaScript. Мы преобразуем, как преобразовать строку в числовой массив, а также в массив строк.

Используйте выражение JSON.parse() для преобразования строки в массив

Выражение JSON.parse() используется для разбора данных, полученных от веб-сервера, на объекты и массивы. Если полученные данные имеют форму объекта JSON, он преобразует их в объект JavaScript. И, если данные представляют собой значение JSON, полученное из массива, JSON.parse() преобразует данные в массив JavaScript. Мы можем использовать JSON.parse() для преобразования строки чисел, разделенных запятыми, в массив. Мы можем объединить скобки со строкой, чтобы преобразовать ее в массив чисел.

Например, создайте переменную data и сохраните в ней значение 0,1,2,3 в виде строки. Используйте JSON.parse() для переменной data и соедините открывающую и закрывающую скобки перед и после переменной. Сохраните выражение в переменной arr . Затем зарегистрируйте переменную в консоли. Также запишите typeof первого элемента массива в консоль.

В приведенном ниже примере мы преобразовали строку чисел в массив чисел. Мы можем узнать тип элементов массива с помощью ключевого слова typeof . Раздел вывода показывает, что элементы массива имеют number тип.

How to convert a string to an array in JavaScript

There are four ways to convert a string to an array in JavaScript:

  1. The String.split() method uses a separator as a delimiter to split the string and returns an array.
  2. The Array.from() method accepts a string as input and returns a character array.
  3. Spread operator ( . ) from ES6 converts the string into a characters array.
  4. The Object.assign() method also takes the string as input and returns a character array.

Note: If you need to convert an array to a string in JavaScript, read this article.

The String.split() method converts a string into an array of substrings using a separator and returns a new array. It splits the string every time it matches against the given separator.

You can also optionally pass in an integer as a second parameter to specify the number of splits.

For a comma-separated string, you can convert it into an array like this:

You can split the string by almost anything: dashes, underscores, or even empty spaces:

If an empty string ( "" ) is used as a separator, the string is split between each character:

To limit the number of items in the array, you can pass in a second parameter to specify the number of splits. For example, let us limit our fruits list to only include the first two items:

The String.split() method works in all modern browsers and back to at least IE 6.

The Array.from() method creates a new Array instance from a given array or iterable object. If you pass in a string to Array.from() , it will be converted to a characters array:

The Array.from() is part of ES6 and only works in modern browsers. However, you can use a polyfill to push the browser support way back to IE6.

A spread operator ( . ) is another modern way to convert a string into an array in ES6:

You can also use the Object.assign() method to convert a string into a characters array, as shown below:

Be careful while using Object.assign() to split a string into an array. This method copies "all enumerable own properties". This method means that it will copy all string properties to the new array.

If the string you are trying to split contains emojis, then String.split() and Object.assign() might not be the best choice. Let us look at the following example:

As you can see above, the 🍕 emoji is converted into two unknown characters. This is because the emojis are unicode characters made up of two characters. The String.split() method attempted to split up the emoji into individual characters.

You should always use the Array.from() or a spread operator for strings containing emojis:

In this article, we looked at 4 different ways to convert a string into an array in JavaScript.

If all you want to do is convert a string into an array of individual characters, you can use any of the above methods. All of them work perfectly fine and produce the same results.

If you want to split a string by a specific character like a comma, dash, empty space, etc., use the String.split() method.

For strings containing emojis, always use the Array.from() method or the spread operator.

Read this article to learn more about JavaScript arrays and how to store multiple values in a single variable.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

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

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