Reputation: 9412
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
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
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
Reputation: 7688
Just simple
var string = '((Sass and Javascript) or (Python and Scala))';
var result = str.match(/[()]|[^()]*/g);
console.log(result)
Upvotes: 1
Reputation: 1279
var string = "abcdeabcde";
string = string.replace(/(/gi, ",(,");
string= string.replace(/)/gi, ",),");
var newstring = string.split(",");
return newstring;
Upvotes: 0
Reputation: 87203
You can use regex
/[()]|[^()]*/g
[()]
: Matches (
or )
exactly once|
: OR[^()]
: Negated class, exclude (
and )
*
: Match zero or more of the preceding classg
: Global matchDemo
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