Javascript split несколько разделителей

Split a string based on multiple delimiters

escape needed for regex related characters +,-,(,),*,?

var x = "adfds+fsdf-sdf"; var separators = [' ', '\\\+', '-', '\\\(', '\\\)', '\\*', '/', ':', '\\\?']; console.log(separators.join('|')); var tokens = x.split(new RegExp(separators.join('|'), 'g')); console.log(tokens); 

Man. The RegEx. This is why I’ve taken so long to actually learn them. Why the heck does the + have three slashes in front, but the * have 2 slashes, and the :, / and space have none?

var separators = [' ', '+', '(', ')', '*', '\\/', ':', '?', '-']; var tokens = x.split(new RegExp('[' + separators.join('') + ']', 'g'));​​​​​​​​​​​​​​​​​ 

Generated regex will be using regex character class: /[ +()*\/:?-]/g

This way you don’t need to escape anything.

The following would be an easier way of accomplishing the same thing.

var tokens = x.split(new RegExp('[-+()*/:? ]', 'g'));​​​​​​​​​​​​​​​​​ 

Note that — must come first (or be escaped), otherwise it will think it is the range operator (e.g. a-z )

I think you would need to escape the +, * and ?, since they’ve got special meaning in most regex languages

This is because characters like + and * have special meaning in Regex.

Change your join from | to |\ and you should be fine, escaping the literals.

I’m getting error when I changed it to |\ ‘Uncaught SyntaxError: Unexpected token ;’ I think it is because when |\ is entered inside quote the quote is getting escaped. How to avoid that?

If you want to split based in multiple regexes and dont want to write a big regex You could use replace and split . Like this:

const spliters = [ /(\[products\])/g, /(\[link\])/g, /(\[llinks\])/g, ]; let newString = "aa [products] bb [link] [products] cc [llinks] dd"; spliters.forEach(regex => < newString = newString.replace(regex, match =>`æææ$æææ`); >); const mySplit = newString.split(/æææ([^æ]+)æææ/) console.log(mySplit);

This works very well for my case.

Источник

split()

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

Синтаксис

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

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

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

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

Читайте также:  Python info about module

Если при записи 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 несколько разделителей

Last updated: Jan 9, 2023
Reading time · 5 min

banner

# Table of Contents

# Split a String with multiple Separators in JavaScript

Use the String.split() method to split a string with multiple separators, e.g. str.split(/[-_]+/) .

The split method can be passed a regular expression containing multiple characters to split the string with multiple separators.

Copied!
const str = 'a-b_c-d'; const arr = str.split(/[-_]+/); console.log(arr); // 👉️ ['a', 'b' , 'c', 'd']

split string with multiple separators

If you’re looking to avoid using regular expressions, scroll down to the example that uses the replaceAll() method.

The String.split() method takes a separator and splits the string into an array on each occurrence of the provided delimiter.

The String.split() method takes the following 2 parameters:

Name Description
separator The pattern describing where each split should occur.
limit An integer used to specify a limit on the number of substrings to be included in the array.
Читайте также:  Ide for python anaconda

We passed a regular expression to the String.split() method.

The forward slashes / / mark the beginning and end of the regular expression.

Copied!
const str = 'a-b_c-d'; const arr = str.split(/[-_]+/); console.log(arr); // 👉️ ['a', 'b' , 'c', 'd']

In the example, we match a hyphen or an underscore.

The plus + matches the preceding item one or more times.

In the example, it matches a hyphen or an underscore one or more times.

You can adjust the separators by adding the characters you need to match between the square brackets.

The following code sample splits by a space and a dot.

Copied!
const str = 'a.b c.d'; const arr = str.split(/[.\s]+/); console.log(arr); // 👉️ ['a', 'b', 'c', 'd']

The \s special character matches whitespace (spaces, tabs and newlines).

You could also use a pipe | (or) to simplify your regular expression, for example a|b matches a or b .

Copied!
const str = 'a.b c.d'; const arr = str.split(/\.|\s/); console.log(arr); // 👉️ ['a', 'b', 'c', 'd']

We used a pipe | (or) symbol in our regular expression. The dot . is a special character, so we had to escape it using a backslash.

The following characters: +,-,(,),*. have a special meaning in regular expressions and have to be escaped using a backslash to be interpreted as a literal character.

This code sample achieves the same result as the regex that used a character class [] .

If you ever need help reading a regular expression, check out this regular expression cheatsheet by MDN.

It contains a table with the name and the meaning of each special character with examples.

If you’re looking to avoid using regular expressions, use the String.replaceAll() method.

# Split a String with multiple Separators using replaceAll

This is a two-step process:

  1. Use the String.replaceAll() method to replace the separators with a single, unified character.
  2. Use the String.split() method to split the string on the unified character.
Copied!
const str = 'one.two three.four'; const arr = str .replaceAll('.', '$') .replaceAll(' ', '$') .split('$'); console.log(arr); // 👉️ ['one', 'two', 'three', 'four']

split string with multiple separators using replaceall

By replacing all occurrences of the multiple separators with the same character, we get a string with a single separator, on which we can use the split() method without any regular expressions.

This is a bit unintuitive at first, but the dollar sign $ doesn’t matter in this example, it could be any character, e.g. a comma or a hyphen.

Copied!
const str = 'one.two three.four'; const arr = str.replaceAll('.', '-') .replaceAll(' ', '-') .split('-'); console.log(arr); // 👉️ ['one', 'two', 'three', 'four']

All we care about is unifying the separators into a single character, which we can pass to the split() method.

Читайте также:  Псевдоклассы

You can define a reusable function if you have to do this often.

Copied!
function splitMultiple(str, separators) let replacedStr = str for (const separator of separators) replacedStr = replacedStr.replaceAll(separator, '$') > return replacedStr.split('$') > const str = 'one.two three.four,five'; // 👇️ [ 'one', 'two', 'three', 'four', 'five' ] console.log(splitMultiple(str, ['.', ' ', ',']))

The splitMultiple function takes a string and an array of separators as parameters and splits the string into an array on each occurrence of a separator.

We used the same approach in the function:

  1. Replace all occurrences of the separators with a unified character (a dollar sign).
  2. Split the string on the unified character (the dollar sign).

# Split a String with multiple Separators using split and join

Alternatively, you could chain calls to the String.split() and Array.join() methods.

Copied!
// ✅ split on each dot and space const str = 'a.b c.d'; const split3 = str .split('.') .join('$') .split(' ') .join('$') .split('$'); console.log(split3); // 👉️ ['a', 'b', 'c', 'd']

split string with multiple separators using split and join

The first call to the split() method splits the string on each dot.

We then join the string with a dollar sign separator.

Copied!
const str = 'a.b c.d'; // 👇️ "a$b c$d" console.log(str.split('.').join('$'));

The next step is to split by a space and join by a dollar sign again.

We are essentially replacing the dots and spaces with dollar signs, so we can unify the two separators into 1 and split using the single separator.

This is a two-step process:

  1. Replace all dots and spaces with a single character.
  2. Split the string by the single character.

I’m not a huge fan of using regular expressions, however, in this scenario, I find the regex approach to be the most intuitive.

The replaceAll() method is also easy to read, but it’s a bit more indirect and takes a second to understand.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

  • Split a String on Capital Letters using JavaScript
  • Split a Full Name into First and Last in JavaScript
  • Split a String and get First or Last Array Element in JS
  • Split on the Last Occurrence of a String in JavaScript
  • Split a Number into an Array in JavaScript
  • Split a String removing any Empty Elements in JavaScript
  • Split a String at a specific Index using JavaScript
  • How to Split a String by Newline in JavaScript
  • How to Split a String by a Regex in JavaScript
  • How to Split a string by Spaces in JavaScript
  • Split a String only on the First Occurrence of a Character
  • Split a String by Special Characters in JavaScript
  • Split a String every N characters in JavaScript

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

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