Bhargav Ponnapalli
Bhargav Ponnapalli

Reputation: 9412

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?

Upvotes: 3

Views: 129

Answers (5)

Anonymous0day
Anonymous0day

Reputation: 3042

var log = function(val){
  console.log(val);
  document.write('<pre>' + JSON.stringify(val , null , ' ') + '</pre>');
  }

var firstStr = '((Sass and Javascript) or (Python and Scala))';
var secondStr = '{>Sass and Javascript< or [Python and Scala]}';


var firstArr = firstStr.match(/[^A-Za-z ]|[A-Za-z ]+/g);
var secondArr = secondStr.match(/[^A-Za-z ]|[A-Za-z ]+/g);

     log(firstArr);
     log(secondArr);
<div id ='el'></div>

Upvotes: 0

Jeremy Jones
Jeremy Jones

Reputation: 5631

You can use capturing parentheses in the split to simplify this a bit. (Note this is apparently not supported by all browsers. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split )

When you use capturing parentheses in a split regex, the captured delimiters are returned in the list along with the 'split' content.

"((Sass and Javascript) or (Python and Scala))".split(/\s*([()])\s*/)

Output

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

You might need to process it afterwards to exclude zero-length elements.

Upvotes: 0

Laxmikant Dange
Laxmikant Dange

Reputation: 7688

Just simple

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

console.log(result)

Upvotes: 1

Rakin
Rakin

Reputation: 1279

var string = "abcdeabcde";
string = string.replace(/(/gi, ",(,");
string= string.replace(/)/gi, ",),");
var newstring = string.split(",");
return newstring;

Upvotes: 0

Tushar
Tushar

Reputation: 87203

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>');

Upvotes: 7

Related Questions