Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Split a string based on a character but retain it in the resulting array

Input

((Sass and Javascript) or (Python and Scala))

Delimiters -"(" and ")"

Output is an Array with the delimiters present as elements

["(","(","Sass and Javascript",")","or","(","Python and Scala",")",")"]

The problem that I am facing is this.

var arr = "((Sass and Javascript) or (Python and Scala))".split(/[(|)]/);
console.log(arr);
document.getElementById("output").innerHTML = arr;
<div id="output"></div>

When I use split on the string, I am losing the "(" and ")" characters and since they might occur anywhere in the string, I will need to insert them into the Array manually. Is there a better way to do this in JS?

like image 440
Bhargav Ponnapalli Avatar asked Feb 21 '26 18:02

Bhargav Ponnapalli


2 Answers

You can use regex

/[()]|[^()]*/g

Regex Demo and Explanation

  1. [()]: Matches ( or ) exactly once
  2. |: OR
  3. [^()]: Negated class, exclude ( and )
  4. *: Match zero or more of the preceding class
  5. g: Global match

Demo

var str = '((Sass and Javascript) or (Python and Scala))';
var matches = str.match(/[()]|[^()]*/g) || [];
matches.pop(); // Remove the last empty match from array

console.log(matches);
document.write('<pre>' + JSON.stringify(matches, 0, 2) + '</pre>');
like image 155
Tushar Avatar answered Feb 23 '26 08:02

Tushar


Just simple

var string = '((Sass and Javascript) or (Python and Scala))';
var result = str.match(/[()]|[^()]*/g);

console.log(result)
like image 43
Laxmikant Dange Avatar answered Feb 23 '26 08:02

Laxmikant Dange