Javascript что такое split

JavaScript String split()

The split() method splits a string into an array of substrings.

The split() method returns the new array.

The split() method does not change the original string.

If (» «) is used as separator, the string is split between words.

See Also

Syntax

Parameters

Parameter Description
separator Optional.
A string or regular expression to use for splitting.
If omitted, an array with the original string is returned.
limit Optional.
An integer that limits the number of splits.
Items after the limit are excluded.

Return Value

More Examples

Split a string into characters and return the second character:

Use a letter as a separator:

If the separator parameter is omitted, an array with the original string is returned:

Browser Support

split() is an ECMAScript1 (ES1) feature.

ES1 (JavaScript 1997) is fully supported in all browsers:

Chrome Edge Firefox Safari Opera IE
Yes Yes Yes Yes Yes Yes

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

split()

split() — метод разбивает строку на массив строк используя для этого заданный разделитель.

Синтаксис

separator — условие по которому будет разделена строка. В качестве разделителя может выступать строковый литерал или регулярное выражение. Также можно использовать специальные символы, например перевод строки, кавычки или юникод. Параметр является необязательным.

Читайте также:  Rotate matrix in javascript

limit — количество элементов, которые должен вернуть метод. Параметр необязательный, если пропустить в массив попадут все подстроки. Если задать, то split() все-равно разделит всю строку по разделителям, но возвратит только указанное количество.

При нахождении разделителя метод удаляет separator и возвращает подстроку.

Если задать в качестве разделителя пустое значение » , тогда каждый символ строки запишется в отдельный элемент массива.

Если при записи split() пропустить separator , то метод вернет массив с одним элементом, который будет содержать всю строку.

Разбить строку по разделителю

 let mySkills = 'Native JavaScript-React-HTML-CSS' mySkills = mySkills.split('-', 2) console.log(mySkills) 

Результатом будет массив с двумя элементами: Native JavaScript и React

Разбить строку на символы

 let myDream = 'Хочу стать frontend разработчиком' let allSymbols = myDream.split('') for (let n = 0; n

Здесь мы разделили строку myDream с помощью split(») , задав в качестве separator пустое значение. Все это записали в allSymbols — теперь там массив, где каждый элемент это символ нашей строки. Далее используя цикл for вывели в console все символы — каждый с новой строки.

Разбить строку используя регулярное выражение

 let topProgramLang = 'JavaScript-Python-Java-C++,PHP,C,C#' topProgramLang = topProgramLang.split(/,|-/) console.log(topProgramLang) 

/,|-/ в этом регулярном выражении мы указали разделители, которые необходимо учесть — запятая и дефис. В итоге получаем массив, где перечислены все языки программирования указанные изначально.

Вывести символы строки в обратном порядке

 let importanceSkills = 'React,TypeScript,CSS,HTML,JavaScript' importanceSkills = importanceSkills.split(',') importanceSkills = importanceSkills.reverse() importanceSkills = importanceSkills.join(', ') console.log(importanceSkills) 

Для того, чтобы решить эту задачу нам понадобятся еще два метода reverse() и join() . Первый перевернет массив, а второй объединит элементы в строку. В итоге получим в console JavaScript, HTML, CSS, TypeScript, React

Сумма элементов массива

 let numForSum = '1,2,5,10,392,19,3,10' numForSum = numForSum.split(',') let sumNum = 0 for (let n = 0; n < numForSum.length; n++) < sumNum += +(numForSum[n]) >console.log(sumNum) 

Выполняя подобные задачи стоит помнить, что метод split() записывает данные в массив в формате строки, поэтому перед тем, как складывать элементы необходимо сначала привести их к числу. Здесь это сделано с помощью + перед выражением. Также можно воспользоваться функцией Number(numForSum[n]) .

Итого

1. Метод split() делит строку по разделителю и записывает все в массив.

2. В получившемся массиве, элементы хранятся в формате текст.

3. В параметрах метода, первым свойством задается разделитель, вторым ограничение на вывод элементов. Оба параметра не обязательны.

Skypro — научим с нуля

Источник

JavaScript split() a String – String to Array JS Method

JavaScript split() a String – String to Array JS Method

If you need to split up a string into an array of substrings, then you can use the JavaScript split() method.

Читайте также:  Сложно ли выучить python

In this article, I will go over the JavaScript split() method and provide code examples.

Basic Syntax of the split() method

Here is the syntax for the JavaScript split() method.

str.split(optional-separator, optional-limit)

The optional separator is a type of pattern that tells the computer where each split should happen.

The optional limit parameter is a positive number that tells the computer how many substrings should be in the returned array value.

JavaScript split() method code examples

In this first example, I have the string «I love freeCodeCamp» . If I were to use the split() method without the separator, then the return value would be an array of the entire string.

const str = 'I love freeCodeCamp'; str.split(); // return value is ["I love freeCodeCamp"]

Examples using the optional separator parameter

If I wanted to change it so the string is split up into individual characters, then I would need to add a separator. The separator would be an empty string.

const str = 'I love freeCodeCamp'; str.split(''); // return value ["I", " ", "l", "o", "v", "e", " ", "f", "r", "e", "e", "C", "o", "d", "e", "C", "a", "m", "p"]

Notice how the spaces are considered characters in the return value.

If I wanted to change it so the string is split up into individual words, then the separator would be an empty string with a space.

const str = 'I love freeCodeCamp'; str.split(' '); // return value ["I", "love", "freeCodeCamp"]

Examples using the optional limit parameter

In this example, I am going to use the limit parameter to return an array of just the first word of the sentence «I love freeCodeCamp» .

const str = 'I love freeCodeCamp'; str.split(' ',1); // return value ["I"]

If I change the limit to be zero, then the return value would be an empty array.

const str = 'I love freeCodeCamp'; str.split(' ',0); //return value []

Should you use the split() method to reverse a string?

The reverse a string exercise is a very popular coding challenge. One common way to solve it involves using the split() method.

In this example, we have the string «freeCodeCamp». If we wanted to reverse the word, then we can chain together the split() , reverse() and join() methods to return the new reversed string.

const str = 'freeCodeCamp'; str.split('').reverse().join(''); //return value "pmaCedoCeerf"

The .split(») portion splits up the string into an array of characters.

Читайте также:  Python str remove symbol

The .reverse() portion reverses the array of characters in place.

The .join(») portion joins the characters together from the array and returns a new string.

This approach seems to work fine for this example. But there are special cases where this would not work.

Let’s take a look at the example provided in the MDN documentation.

If we tried to reverse the string «mañana mañana», then it would lead to unexpected results.

const str = 'mañana mañana' const reversedStr = str.split('').reverse().join('') console.log(reversedStr) // return value would be "anãnam anañam"

Notice how the tilde(~) is placed over the letter «a» instead of «n» in the reversed word. This happens because our string contains what is called a grapheme.

A grapheme cluster is a series of symbols combined to produce one single character that humans can read on screen. When we try to reverse the string using these types of characters, the computer can misinterpret these characters and produce an incorrect version of the reversed string.

If we just isolate the split method, you can see how the computer is breaking up each individual character.

const str = 'mañana mañana' console.log(str.split('')) //["m", "a", "ñ", "a", "n", "a", " ", "m", "a", "n", "̃", "a", "n", "a"]

There are packages that you can use in your projects to fix this issue and reverse the string correctly if you are using these special characters.

Conclusion

The JavaScript split() method is used to split up a string into an array of substrings.

Here is syntax for the JavaScript split() method.

str.split(optional-separator, optional-limit)

The optional separator is a type of pattern that tells the computer where each split should happen.

The optional limit parameter is a positive number that tells the computer how many substrings should be in the returned array value.

You could use the split method to reverse a string, but there are special cases where this would not work. If your string contains grapheme clusters, then the result might produce an incorrectly reversed word.

You could also choose to use the spread syntax to split up the string before reversing it.

const str = 'mañana mañana' console.log([. str].reverse().join(""))

I hope you enjoyed this article and best of luck on your JavaScript journey.

Источник

Оцените статью