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?
You can use regex
/[()]|[^()]*/g
Regex Demo and Explanation
[()]: 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>');
Just simple
var string = '((Sass and Javascript) or (Python and Scala))';
var result = str.match(/[()]|[^()]*/g);
console.log(result)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With