I am trying to split the string into an array of strings those matching a regular expression and those that don't:
string = "Lazy {{some_animal}} jumps over.."
# do some magic with regex /({{\s?[\w]+\s?}})/g and its negation
array = ["Lazy ", "{{some_animal}}", " jumps over.."]
Best performant way to do that in javascript?
You can use String match for that
The regex below simply matches anything that's not a mustach, optionally surrounded by mustaches.
Example snippet:
var str = "Lazy {{some_animal}} jumps over..";
const pattern = /\{*[^{}]+\}*/g;
var array = str.match(pattern);
console.log(str);
console.log(pattern);
console.log(array);
But to make it more precise, the regex pattern becomes a bit more complicated.
The regex below matches:
var str = "Lazy {{some_animal}} jumps over..";
const pattern = /\{\{\w+\}\}|.+?(?=\{\{\w+\}\})|.+/g;
var array = str.match(pattern);
console.log(str);
console.log(pattern);
console.log(array);
And last but not least, the evil SM method.
Split AND Match on the same regex. And concatinate them into a single array.
The downside of this method is that the order is not preserved.
var str = "Lazy {{some_animal}} jumps over..";
const pattern = /\{\{\w+\}\}/g;
var what_you_want = str.match(pattern);
var what_you_dont_want = str.split(pattern);
var array = what_you_want.concat(what_you_dont_want);
console.log(str);
console.log(pattern);
console.log(array);
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