For example, there is a line:
const string = "a {{bcd}} e {{f}}"
The result will be an array like this:
const result = ["a", "{{bcd}}", "e", "{{f}}"];
I tried the following code, but the regex result was sent to the array.
let string = "a {{bcd}} e {{f}}"
string = string.replace(/s+/g, "");
const reg = /({{(.*?)}})/g
const a = string.split(reg);
console.log(a);
It turns out that it still saves the regex, but this is not necessary.
3
Answers
To achieve the desired result, you can use a combination of regular expressions and the
match
method. Here’s a code example that splits the input string into an array while keeping the "((…))" parts intact:In this code:
inputString
as"a ((bcd)) e ((f))"
.regex
that matches everything between "((…))" while excluding the parentheses themselves.split
method to split the input string using this regular expression. This will result in an array where the "((…))" parts are separated.filter(Boolean)
to remove any empty strings from the resulting array.result
array, which should contain the desired output:["a", "((bcd))", "e", "((f))"]
.This code should give you the expected result.
You can use
String::matchAll()
to iterate all matches in a string and collect the capture groups:An one-liner:
Explanation
You could define the multiple combination of regex to match either "((…))" or any other character to capture all the possible substrings.
After you get all the possible substrings in list, filter those empty using filter
Code